home *** CD-ROM | disk | FTP | other *** search
/ Komputer for Alle 2001 #12 / CD 12 (Black) - 2001.iso / Flash / flash5-trial.exe / data1.cab / App_Files / Help / ActionScriptReference / out.txt < prev    next >
Encoding:
Text File  |  2000-08-29  |  227.8 KB  |  331 lines

  1. <url>html/00_intro1.html</url>
  2. <title>Getting started: Overview</title> Getting started: Overview Getting Started > Getting started: Overview ActionScript is Flash's scripting language. You can use ActionScript to control objects in Flash movies to create navigation and interactive elements and to extend Flash to create highly interactive movies and Web applications.
  3.  
  4. <url>html/00_intro10.html</url>
  5. <title>Clip actions</title> What's new in Flash 5 ActionScript Getting Started > What's new in Flash 5 ActionScript > Clip actions You can use the onClipEvent action to assign actions directly to movie clip instances on the Stage. The onClipEvent action has events such as load , enterFrame , mouseMove , and data that allow you to create new kinds of advanced interactivity.
  6.  
  7. <url>html/00_intro11.html</url>
  8. <title>New actions</title> What's new in Flash 5 ActionScript Getting Started > What's new in Flash 5 ActionScript > New actions You can use new actions such as do..while and for to create complex loops. Other new actions are implemented as methods of the MovieClip object; for example, getBounds , attachMovie , hitTest , swapDepths , and globalToLocal .
  9.  
  10. <url>html/00_intro12.html</url>
  11. <title>Smart Clips</title> What's new in Flash 5 ActionScript Getting Started > What's new in Flash 5 ActionScript > Smart Clips Smart Clips have internal scripts that you, or another developer, can change without using the Actions panel. You can pass values to a Smart Clip through clip parameters that you can define in the Library.
  12.  
  13. <url>html/00_intro13.html</url>
  14. <title>Debugger</title> What's new in Flash 5 ActionScript Getting Started > What's new in Flash 5 ActionScript > Debugger The Debugger allows you to view and change variable and property values in a movie playing in Test-movie mode, the stand-alone Flash Player, or a Web browser. This allows you to easily find problems in your ActionScript.
  15.  
  16. <url>html/00_intro14.html</url>
  17. <title>XML support</title> What's new in Flash 5 ActionScript Getting Started > What's new in Flash 5 ActionScript > XML support The predefined XML object allows you to convert ActionScript to XML documents and pass them to server-side applications. You can also use the XML object to load XML documents into a Flash movie and interpret them. The predefined XMLSocket object allows you to create a continuous server connection to pass XML data for real-time applications.
  18.  
  19. <url>html/00_intro15.html</url>
  20. <title>Using Flash Help for actions</title> Using Flash Help for actions Getting Started > Using Flash Help for actions Flash 5 contains context-sensitive help for each action available in the Actions panel. While you're creating scripts, you can get information on the actions you're using. To get help on actions: 1 In the Actions panel, select an action in the Toolbox list. 2 Click the Help button at the top of the panel. The topic related to the action appears in the browser.
  21.  
  22. <url>html/00_intro2.html</url>
  23. <title>What's new in Flash 5 ActionScript</title> What's new in Flash 5 ActionScript Getting Started > What's new in Flash 5 ActionScript Flash 5 ActionScript offers exciting new features for creating immersive, interactive Web sites with sophisticated games, forms, surveys, and real-time interactivity such as chat systems. Flash 5 ActionScript has many new features and syntax conventions that make it similar to the core JavaScript programming language. This manual will explain basic programming concepts such as functions, variables, statements, operators, conditionals, and loops. The ActionScript Dictionary contains a detailed entry for every ActionScript element. This manual does not attempt to teach programming in general. There are many resources available that provide more information about general programming concepts and the JavaScript language. The European Computers Manufacturers Association (ECMA) wrote a document called ECMA-262 that was derived from JavaScript to serve as the international standard for the JavaScript language. ActionScript is based on the ECMA-262 specification . Netscape DevEdge Online has a JavaScript Developer Central that contains documentation and articles useful for understanding ActionScript. The most valuable resource is the Core JavaScript Guide .
  24.  
  25. <url>html/00_intro3.html</url>
  26. <title>Differences between ActionScript and JavaScript</title> What's new in Flash 5 ActionScript Getting Started > What's new in Flash 5 ActionScript > Differences between ActionScript and JavaScript You don't need to know JavaScript to use and learn ActionScript. If you know JavaScript, however, ActionScript will appear familiar to you. Some of the differences between ActionScript and JavaScript are as follows: ActionScript does not support browser-specific objects such as Document, Window, and Anchor. ActionScript does not completely support all of the JavaScript predefined objects. ActionScript supports syntax constructs that are not permitted in JavaScript (for example, the tellTarget and ifFrameLoaded actions and slash syntax). ActionScript does not support some JavaScript syntax constructs, such as switch , continue , try , catch , throw , and statement labels. ActionScript does not support the JavaScript Function constructor. In ActionScript, the eval action can only perform variable references . In JavaScript, toString of undefined is undefined. In Flash 5, for Flash 4 compatibility, toString of undefined is " " . In JavaScript, evaluating undefined in a numeric context results in NaN . In Flash 5, for Flash 4 compatibility, evaluating undefined results in 0 . ActionScript does not support Unicode; it supports ISO-8859-1 and Shift-JIS character sets.
  27.  
  28. <url>html/00_intro4.html</url>
  29. <title>Text editing</title> What's new in Flash 5 ActionScript Getting Started > What's new in Flash 5 ActionScript > Text editing You can enter scripts directly into the Actions panel in Expert Mode. You can also choose elements from a pop-up menu or a Toolbox list just like you did in Flash 4.
  30.  
  31. <url>html/00_intro5.html</url>
  32. <title>Dot syntax</title> What's new in Flash 5 ActionScript Getting Started > What's new in Flash 5 ActionScript > Dot syntax You can use dot syntax to get and set the properties and methods of an object, including movie clip instances and variables. You can use dot syntax instead of the slash syntax used in Flash 4. Slash syntax is no longer preferred, but it is still supported by the Flash Player.
  33.  
  34. <url>html/00_intro6.html</url>
  35. <title>Data types</title> What's new in Flash 5 ActionScript Getting Started > What's new in Flash 5 ActionScript > Data types Flash 5 ActionScript supports the following data types: string, number, boolean, object, and movie clip. Multiple data types allow you to use different types of information in ActionScript. For example, you can create arrays and associative arrays.
  36.  
  37. <url>html/00_intro7.html</url>
  38. <title>Local variables</title> What's new in Flash 5 ActionScript Getting Started > What's new in Flash 5 ActionScript > Local variables You can declare local variables that expire at the end of the action list or function call. This allows you to manage memory and reuse variable names. Flash 4 variables were all permanent—even temporary variables like loop counters remained in the movie until the movie ended.
  39.  
  40. <url>html/00_intro8.html</url>
  41. <title>User-defined functions</title> What's new in Flash 5 ActionScript Getting Started > What's new in Flash 5 ActionScript > User-defined functions You can define functions with parameters that return values. This allows you to reuse blocks of code in your scripts. In Flash 4, you could reuse code by using the call action, but you couldn't pass parameters or return values.
  42.  
  43. <url>html/00_intro9.html</url>
  44. <title>Predefined objects</title> What's new in Flash 5 ActionScript Getting Started > What's new in Flash 5 ActionScript > Predefined objects You can use predefined objects to access and manipulate certain types of information. The following are a few of the predefined objects: The Math object features a full complement of built-in mathematical constants and functions, such as E (Euler's constant), cos (Cosine), and atan (Arctangent). The Date object allows you to get information about the date and time on whatever system is running the Flash Player. The Sound object allows you to add sounds to a movie and control sounds in a movie as it plays. For example, you can adjust volume ( setVolume ), or balance ( setPan ). The Mouse object allows you to hide the standard cursor so that you can use a custom cursor. The MovieClip object allows you to control movie clips without using a wrapper action such as tellTarget . You can call a method such as play , loadMovie , or duplicateMovieClip from an instance name by using dot syntax (for example, myMovieClip.play() ).
  45.  
  46. <url>html/01_understanding1.html</url>
  47. <title>Understanding ActionScript: Overview</title> Understanding ActionScript: Overview Understanding ActionScript > Understanding ActionScript: Overview ActionScript, Flash's scripting language, adds interactivity to a movie. You can set up your movie so that user events, such as button clicks and keypresses, trigger scripts that tell the movie what action to perform. For example, you can write a script that tells Flash to load different movies into the Flash Player depending on which navigation button a user chooses. Think of ActionScript as a tool that allows you to create a movie that behaves exactly as you want. You don't need to understand every possible use of the tool to begin scripting; if you have a clear goal, you can start building scripts with simple actions. You can incorporate new elements of the language as you learn them to accomplish more complicated tasks. This chapter introduces you to ActionScript as an object-oriented scripting language and provides an overview of ActionScript terms. It also deconstructs a sample script so that you can begin to focus on the bigger picture. This chapter also introduces you to the Actions panel, where you can build scripts by selecting ActionScript elements or entering text into the Script window.
  48.  
  49. <url>html/01_understanding10.html</url>
  50. <title>Using the Actions panel</title> Using the Actions panel Understanding ActionScript > Using the Actions panel The Actions panel lets you create and edit actions for an object or frame using two different editing modes. You can select prewritten actions from the Toolbox list, drag and drop actions, and use buttons to delete or rearrange actions. In Normal Mode you can write actions using parameter (argument) fields that prompt you for the correct arguments. In Expert Mode you can write and edit actions directly in a text box, much like writing script with a text editor. To display the Actions panel: Choose Window > Actions. Selecting an instance of a button or movie clip makes the Actions panel active. The Actions panel title changes to Object Actions if a button or movie clip is selected, and to the Frame Actions panel if a frame is selected. To select an editing mode: 1 With the Actions panel displayed, click the arrow in the upper right corner of the panel to display the pop-up menu. 2 Choose Normal Mode or Expert Mode from the pop-up menu. Each script maintains its own mode. For example, you can script one instance of a button in Normal Mode, and another in Expert Mode. Switching between the selected button then switches the panel's mode state. For more information, see Normal Mode and Expert Mode .
  51.  
  52. <url>html/01_understanding11.html</url>
  53. <title>Normal Mode</title> Using the Actions panel Understanding ActionScript > Using the Actions panel > Normal Mode In Normal Mode you create actions by selecting actions from a list on the left side of the panel, called the Toolbox list. The Toolbox list contains Basic Actions, Actions, Operators, Functions, Properties, and Objects categories. The Basic Actions category contains the simplest Flash actions and is only available in Normal Mode. The selected actions are listed on the right side of the panel, in the Actions list. You can add, delete, or change the order of action statements; you can also enter parameters (arguments) for actions in parameter fields at the bottom of the panel. In Normal Mode you can use the controls in the Actions panel to delete or change the order of statements in the Actions list. These controls are especially useful for managing frame or button actions that have several statements. The Actions panel in Normal Mode.   To select an action: 1 Click an Actions category in the toolbox to display the actions in that category. 2 Double-click an action or drag it to the Script window. To use the Parameters fields: 1 Click the Parameters button in the lower right corner of the Actions panel to display the fields. 2 Select the action and enter new values in the Parameters fields to change parameters of existing actions. To insert a movie clip target path: 1 Click the Target Path button in the lower right corner of the Actions panel to display the Insert Target Path dialog box. 2 Select a movie clip from the display list. To move a statement up or down the list: 1 Select a statement in the Actions list. 2 Click the Up or Down Arrow buttons. To delete an action: 1 Select a statement in the Actions list. 2 Click the Delete (-) button. To change the parameters of existing actions: 1 Select a statement in the Actions list. 2 Enter new values in the Parameters fields. To resize the Toolbox or Actions list, do one of the following: Drag the vertical splitter bar that appears between the Toolbox and Actions list. Double-click the splitter bar to collapse the Toolbox list; double-click the bar again to redisplay the list. Click the Left or Right Arrow button on the splitter bar to expand or collapse the list. When the Toolbox list is hidden, you can still access its items using the Add (+) button in the upper left of the Actions panel.
  54.  
  55. <url>html/01_understanding12.html</url>
  56. <title>Expert Mode</title> Using the Actions panel Understanding ActionScript > Using the Actions panel > Expert Mode In Expert Mode you create actions by entering ActionScript into the text box on the right side of the panel or by selecting actions from the Toolbox list on the left. You edit actions, enter parameters for actions, or delete actions directly in the text box, much like creating script in a text editor. Expert Mode lets advanced ActionScript users edit their scripts with a text editor, as they would JavaScript or VBScript. Expert Mode differs from Normal Mode in these ways: Selecting an item using the Add (+) button or Toolbox list inserts the item in the text-editing area. No parameter fields appear. In the button panel, only the Add (+) button works. The Up and Down Arrow buttons remain inactive. The Actions panel in Expert Mode  
  57.  
  58. <url>html/01_understanding13.html</url>
  59. <title>Switching between editing modes</title> Using the Actions panel Understanding ActionScript > Using the Actions panel > Switching between editing modes Changing editing modes while writing a script can change the formatting of the script. For that reason, it is best to use one editing mode per script. When you switch from Normal to Expert Mode, indentation and formatting is maintained. Although you can convert Normal Mode scripts with errors to Expert Mode, you cannot export the scripts until the errors are fixed. Switching from Expert to Normal Mode is slightly more complex: When you switch to Normal Mode, Flash reformats the script and strips any white space and indentation you've added. If you switch to Normal Mode and then back to Expert Mode, Flash reformats the script according to its appearance in Normal Mode. Expert Mode scripts containing errors cannot be exported or converted to Normal Mode; if you try to convert the script, you'll receive an error message. To switch editing modes: Choose Normal Mode or Expert Mode from the pop-up menu at the upper right of the Actions panel. A check mark indicates the selected mode. To set an editing mode preference: 1 Choose Edit > Preferences. 2 Select the General tab 3 In the Actions Panel section, select Normal Mode or Expert Mode from the pop-up menu.
  60.  
  61. <url>html/01_understanding14.html</url>
  62. <title>Using an external editor</title> Using the Actions panel Understanding ActionScript > Using the Actions panel > Using an external editor Although the Actions panel's Expert Mode gives you more control when editing ActionScript, you can also choose to edit a script outside Flash. You can then use the include action to add the scripts you wrote in the external editor to a script within Flash. For example, the following statement imports a script file: #include "externalfile.as" The text of the script file replaces the include action. The text file must be present when the movie is exported. To add the scripts written in an external editor to a script within Flash: 1 Drag include from the Toolbox list to the Script window. 2 Enter the path to the external file in the Path box. The path should be relative to the FLA file. For example, if myMovie.fla and externalfile.as were in the same folder, the path would be externalfile.as. If externalfile.as was in a subfolder called Scripts, the path would be scripts/externalfile.as.
  63.  
  64. <url>html/01_understanding15.html</url>
  65. <title>Choosing Actions panel options</title> Using the Actions panel Understanding ActionScript > Using the Actions panel > Choosing Actions panel options The Actions panel allows you to work with scripts in a variety of ways. You can change the font size in the Script window. You can import a text file containing ActionScript into the Actions panel and export actions as a text file, search and replace text in a script, and use syntax highlighting to make scripts easier to read and errors easier to detect. The Actions panel displays warning highlights for syntax errors and Flash Player version incompatibilities. It also highlights deprecated , or no longer preferable, ActionScript elements. These Actions panel options are available in both Normal and Expert Modes unless otherwise noted. To change the font size in the Script window: 1 From the pop-up menu at the upper right of the Actions panel, choose Font Size. 2 Select Small, Normal, or Large. To import a text file containing ActionScript: 1 From the pop-up menu at the upper right of the Actions panel, choose Import from File. 2 Select a text file containing ActionScript, and click Open. Note: Scripts with syntax errors can only be imported in Expert Mode. In Normal Mode, you'll receive an error message. To export actions as a text file: 1 From the pop-up menu at the upper right of the Actions panel, Choose Export as File. 2 Choose a location where the file will be saved, and click Save. To print actions: 1 From the pop-up menu at the upper right of the Actions panel, choose Print. The Print dialog box appears. 2 Choose Options and click Print. Note: The printed file will not include information about its originating Flash file. It's a good idea to include this information in a comment action in the script. To search for text in a script, choose an option from the Actions panel pop-up menu: Choose Goto Line to go to a specific line in a script. Choose Find to find text. Choose Find Again to find text again. Choose Replace to find and replace text. In Expert Mode, Replace scans the entire body of text in a script. In Normal Mode, Replace searches and replaces text only in the parameter field of each action. For example, you cannot replace all gotoAndPlay actions with gotoAndStop in Normal Mode. Note: Use the Find or Replace command to search the current Actions list. To search through text in every script in a movie, use the Movie Explorer. For more information, see Flash Help.
  66.  
  67. <url>html/01_understanding16.html</url>
  68. <title>Highlighting and checking syntax</title> Using the Actions panel Understanding ActionScript > Using the Actions panel > Highlighting and checking syntax Syntax highlighting identifies certain ActionScript elements with specific colors. This helps prevent syntax errors such as incorrect capitalization of keywords. For example, if the keyword typeof was spelled typeOf , it would not be blue and you could recognize the error. When syntax highlighting is turned on, text is highlighted in the following way: Keywords and predefined identifiers (for example, gotoAndStop , play , and stop ) are blue. Properties are green. Comments are magenta. Strings surrounded by quotation marks are gray. To turn syntax highlighting on or off: Choose Colored Syntax from the pop-up menu at the upper right of the Actions panel. A check mark indicates that the option is turned on. All scripts in your movie will be highlighted. It's a good idea to check a script's syntax for errors before exporting a movie. Errors are reported in the Output window. You can export a movie that contains erroneous scripts. However, you will be warned that scripts containing errors were not exported. To check the current script's syntax for errors: Choose Check Syntax from the pop-up menu at the upper right of the Actions panel.
  69.  
  70. <url>html/01_understanding17.html</url>
  71. <title>About error highlighting</title> Using the Actions panel Understanding ActionScript > Using the Actions panel > About error highlighting All syntax errors are highlighted with a solid red background in the Script window in Normal Mode. This makes it easy to spot problems. If you move the mouse pointer over an action with incorrect syntax, a tooltip displays the error message associated with that action. When you select the action, the error message is also displayed in the pane title of the parameters area. In Normal Mode all ActionScript export incompatibilities are highlighted with a solid yellow background in the Script window. For example, if the Flash Player export version is set to Flash 4, ActionScript that is supported only by the Flash 5 Player is highlighted in yellow. The export version is determined in the Publish Settings dialog box. All deprecated actions are highlighted with a green background in the toolbox. Deprecated actions are only highlighted when the Flash export version is set to Flash 5. To set the Flash Player export version: 1 Choose File > Publish Settings. 2 Click the Flash tab. 3 Choose an export version from the Version pop-up menu. Note: You cannot turn off syntax error highlighting. To show deprecated syntax highlighting: Choose Show Deprecated Syntax from the Actions panel pop-up menu. For a complete list of all error messages, see Table of error messages .
  72.  
  73. <url>html/01_understanding18.html</url>
  74. <title>Assigning actions to objects</title> Assigning actions to objects Understanding ActionScript > Assigning actions to objects You can assign an action to a button or a movie clip to make an action execute when the user clicks a button or rolls the pointer over it, or when the movie clip loads or reaches a certain frame. You assign the action to an instance of the button or movie clip; other instances of the symbol aren't affected. (To assign an action to a frame, see Assigning actions to frames .) When you assign an action to a button, you must nest the action inside an on(mouse event) handler and specify the mouse or keyboard events that trigger the action. When you assign an action to a button in Normal Mode, the on(mouse event) handler is automatically inserted. When you assign an action to a movie clip, you must nest the action inside an onClipEvent handler and specify the clip event that triggers the action. When you assign an action to a movie clip in Normal Mode, the on(mouse event) handler is automatically inserted. The following instructions describe how to assign actions to objects using the Actions panel in Normal Mode. Once you've assigned an action, use the Control > Test Movie command to test whether it works. Most actions won't work in Editing Mode. To assign an action to a button or movie clip: 1 Select a button or movie clip instance and choose Window > Actions. If the selection is not a button, a movie clip instance, or a frame, or if the selection includes multiple objects, the Actions panel is dimmed. 2 Choose Normal Mode from the pop-up menu at the upper right of the Object Actions panel. 3 To assign an action, do one of the following: Click the Actions folder in the Toolbox list on the left side of the Actions panel. Double-click an action to add it to the Actions list on the right side of the panel. Drag an action from theToolbox list to the Actions list. Click the Add (+) button and choose an action from the pop-up menu. Use the keyboard shortcut listed next to each action in the pop-up menu. Selecting an object from the toolbox in Normal Mode   4 In the Parameters fields at the bottom of the panel, select parameters for the action as needed. Parameters vary depending on the action you choose. For detailed information on the required parameters for each action, see the ActionScript dictionary: Overview. To insert a Target path for a movie clip into a Parameter field, click the Target Path button in the lower right corner of the Actions panel. For more information, see Working with movie clips: Overview . 5 Repeat steps 3 and 4 to assign additional actions as necessary. To test an object action: Choose Control > Test Movie.
  75.  
  76. <url>html/01_understanding19.html</url>
  77. <title>Assigning actions to frames</title> Assigning actions to frames Understanding ActionScript > Assigning actions to frames To make a movie do something when it reaches a keyframe, you assign a frame action to the keyframe. For example, to create a loop in the Timeline between frames 20 and 10, you would add the following frame action to frame 20: gotoAndPlay (10); It's a good idea to place frame actions in a separate layer. Frames with actions display a small a in the Timeline. An "a" in a keyframe indicates a frame action.   Once you've assigned an action, choose Control > Test Movie to test whether it works. Most actions won't work in Editing Mode. The following instructions describe how to assign frame actions using the Actions panel in Normal Mode. (For information on assigning an action to a button or movie clip, see Assigning an action or method .) To assign an action to a keyframe: 1 Select a keyframe in the Timeline and choose Window > Actions. If a selected frame is not a keyframe, the action is assigned to the previous keyframe. If the selection is not a frame, or if the selection includes multiple keyframes, the Actions panel is dimmed. 2 Choose Normal Mode from the pop-up menu at the upper right of the Frame Actions panel. 3 To assign an action, do one of the following: Click the Actions folder in the Toolbox list on the left side of the Actions panel. Double-click an action to add it to the Actions list on the right side of the panel. Drag an action from theToolbox list to the Actions list. Click the Add (+) button and choose an action from the pop-up menu. Use the keyboard shortcut listed next to each action in the pop-up menu. In the Parameters fields at the bottom of the panel, select parameters for the action as needed. 4 To assign additional actions, select another keyframe and repeat step 3. To test a frame action: Choose Control > Test Movie.
  78.  
  79. <url>html/01_understanding2.html</url>
  80. <title>About scripting in ActionScript</title> About scripting in ActionScript Understanding ActionScript > About scripting in ActionScript You can start writing simple scripts without knowing much about ActionScript. All you need is a goal; then it's just a matter of picking the right actions. The best way to learn how simple ActionScript can be is to create a script. The following steps attach a script to a button that changes the visibility of a movie clip. To change the visibility of a movie clip: 1 Choose Window > Common Libraries > Buttons, and then choose Window > Common Libraries > Movie Clips. Place a button and a movie clip on the Stage. 2 Select the movie clip instance on the Stage, and choose Window > Panels > Instance Properties. 3 In the Name field, enter testMC . 4 Select the button on the Stage, and choose Window > Actions to open the Actions panel. 5 In the Object Actions panel, click the Actions category to open it. 6 Double-click the setProperty action to add it to the Actions list. 7 From the Property pop-up menu, choose _visible (Visibility). 8 For the Target parameter, enter testMC . 9 For the Value parameter, enter 0 . The code should look like this: on (release) { setProperty ("testMC", _visible, false); } 10 Choose Control > Test Movie and click the button to see the movie clip disappear. ActionScript is an object-oriented scripting language. This means that actions control objects when a particular event occurs. In this script, the event is the release of the mouse, the object is the movie clip instance testMC , and the action is setProperty . When the user clicks the onscreen button, a release event triggers a script that sets the _visible property of the object MC to false and causes the object to become invisible. You can use the Actions panel to guide you through setting up simple scripts. To use the full power of ActionScript, it is important to understand how the language works: the concepts, elements, and rules that the language uses to organize information and create interactive movies.
  81.  
  82. <url>html/01_understanding3.html</url>
  83. <title>About planning and debugging scripts</title> About scripting in ActionScript Understanding ActionScript > About scripting in ActionScript > About planning and debugging scripts When you write scripts for an entire movie, the quantity and variety of scripts can be large. Deciding which actions to use, how to structure scripts effectively, and where scripts should be placed requires careful planning and testing, especially as the complexity of your movie grows. Before you begin writing scripts, formulate your goal and understand what you want to achieve. This is as important—and typically as time consuming—as developing storyboards for your work. Start by writing out what you want to happen in the movie, as in this example: I want to create my whole site using Flash. Site visitors will be asked for their name, which will be reused in messages throughout the site. The site will have a draggable navigation bar with buttons that link to each section of the site. When a button is clicked, the new section will fade in to the center of the Stage. One scene will have a contact form with the user's name already filled in. When you know what you want, you can build the objects you need and write the scripts to control those objects. Getting scripts to work the way you want takes time—often more than one cycle of writing, testing, and debugging. The best approach is to start simple and test your work frequently. When you get one part of a script working, choose Save As to save a version of the file (for example, myMovie01.fla) and start writing the next part. This approach will help you identify bugs efficiently and ensure that your ActionScript is solid as you write more complex scripts.
  84.  
  85. <url>html/01_understanding4.html</url>
  86. <title>About object-oriented scripting</title> About scripting in ActionScript Understanding ActionScript > About scripting in ActionScript > About object-oriented scripting In object-oriented scripting, you organize information by arranging it into groups called classes . You can create multiple instances of a class, called objects, to use in your scripts. You can use ActionScript's predefined classes and create your own. When you create a class, you define all the properties (characteristics) and methods (behaviors) of each object it creates, just as real-world objects are defined. For example, a person has properties such as gender, height, and hair color and methods such as talk, walk, and throw. In this example, "person" is a class and each individual person is an object, or an instance of that class. Objects in ActionScript can contain data or they can be graphically represented on the Stage as movie clips. All movie clips are instances of the predefined class MovieClip. Each movie clip instance contains all the properties (for example, _height , _rotation , _totalframes ) and all the methods (for example, gotoAndPlay , loadMovie , startDrag ) of the MovieClip class. To define a class, you create a special function called a constructor function ; predefined classes have constructor functions that are already defined. For example, if you want information about a bicycle rider in your movie, you could create a constructor function, Biker , with the properties time and distance and the method rate , which tells you how fast the biker is traveling: function Biker(t, d) { this.time = t; this.distance = d; } function Speed() { return this.time / this.distance; } Biker.prototype.rate = Speed; You could then create copies—that is, instances—of the class. The following code creates instances of the object Biker called emma and hamish . emma = new Biker(30, 5); hamish = new Biker(40, 5); Instances can also communicate with each other. For the Biker object, you could create a method called shove that lets one biker shove another biker. (The instance emma could call its shove method if hamish got too close.) To pass information to a method, you use parameters (arguments): for example, the shove method could take the parameters who and howFar . In this example emma shoves hamish 10 pixels: emma.shove(hamish, 10); In object-oriented scripting, classes can receive properties and methods from each other according to a specific order; this is called inheritance . You can use inheritance to extend or redefine the properties and methods of a class. A class that inherits from another class is called a subclass . A class that passes properties and methods to another class is called a superclass . A class can be both a subclass and a superclass.
  87.  
  88. <url>html/01_understanding5.html</url>
  89. <title>About the MovieClip object</title> About scripting in ActionScript Understanding ActionScript > About scripting in ActionScript > About the MovieClip object ActionScript's predefined classes are called objects . Each object allows you to access a certain type of information. For example, the Date object has methods (for example, getFullYear , getMonth) , that allow you to read information from the system clock. The Sound object has methods (for example, setVolume , setPan ) that allow you to control a sound in a movie. The MovieClip object has methods that allow you to control movie clip instances (for example, play , stop , and getURL ) and get and set information about their properties (for example, _alpha , _framesloaded , _visible ). Movie clips are the most important objects of a Flash movie because they have Timelines that run independently of each other. For example, if the main Timeline only has one frame and a movie clip in that frame has ten frames, each frame in the movie clip will still play. This allows instances to act as autonomous objects that can communicate with each other. Movie clip instances each have a unique instance name so that you can target them with an action. For example, you may have multiple instances on the Stage (for example, leftClip and rightClip ) and only want one to play at a time. To assign an action that tells one particular instance to play, you need to use its name. In the following example, the movie clip's name is leftClip : leftClip.play(); Instance names also allow you to duplicate, remove, and drag movie clips while a movie plays. The following example duplicates the instance cartItem to fill out a shopping cart with the number of items purchased: onClipEvent(load) { do { duplicateMovieClip("cartItem", "cartItem" + i, i); i = i + 1; } while (i <= numberItemsPur); } Movie clips have properties whose values you can set and retrieve dynamically with ActionScript. Changing and reading these properties can change the appearance and identity of a movie clip and is the key to creating interactivity. For example, the following script uses the setProperty action to set the transparency (alpha setting) of the navigationBar instance to 10: setProperty("navigationBar", _alpha, 10); For more information about other types of objects, see Using predefined objects .
  90.  
  91. <url>html/01_understanding6.html</url>
  92. <title>How scripts flow</title> About scripting in ActionScript Understanding ActionScript > About scripting in ActionScript > How scripts flow ActionScript follows a logical flow. Flash executes ActionScript statements starting with the first statement and continuing in order until it reaches the final statement or a statement that instructs ActionScript to go somewhere else. Some actions that send ActionScript somewhere other than the next statement are if statements, do...while loops, and the return action.    A flow chart of the if..else action  A flow chart of the do..while action   An if statement is called a conditional statement or a "logical branch" because it controls the flow of a script based on the evaluation of a certain condition. For example, the following code checks to see if the value of the number variable is less than or equal to 10. If the check returns true (for example, the value of number is 5), the variable alert is set and displays its value in an input text field, as in the following: if (number <= 10) { alert = "The number is less than or equal to 10"; } You can also add else statements to create a more complicated conditional statement. In the following example, if the condition returns true (for example, the value of number is 3), the statement between the first set of curly braces runs and the alert variable is set in the second line. If the condition returns false (for example, the value of number is 30), the first block of code is skipped and the statement between the curly braces after the else statement runs, as in the following: if (number <= 10) { alert = "The number is less than or equal to 10"; } else { alert = "The number is greater than 10"; } For more information, see Using "if" statements . Loops repeat an action a certain number of times or until a certain condition is met. In the following example, a movie clip is duplicated five times: i = 0; do { duplicateMovieClip ("myMovieClip", "newMovieClip" + i, i); newName = eval("newMovieClip" + i); setProperty(newName, _x, getProperty("myMovieClip", _x) + (i * 5)); i = i + 1; } while (i <= 5); For detailed information, see Repeating an action .
  93.  
  94. <url>html/01_understanding7.html</url>
  95. <title>Controlling when ActionScript runs</title> About scripting in ActionScript Understanding ActionScript > About scripting in ActionScript > Controlling when ActionScript runs When you write a script, you use the Actions panel. The Actions panel allows you to attach the script to a frame on the main Timeline or the Timeline of any movie clip, or to either a button or movie clip on the Stage. Flash executes actions at different times, depending on what they're attached to: Actions attached to a frame are executed when the playhead enters that frame. Actions attached to a button are enclosed in an on handler action. Actions attached to a movie clip are enclosed in an onClipEvent handler action. The onClipEvent and on actions are called handlers because they "handle" or manage an event. (An event is an occurrence such as a mouse movement, a keypress, or a movie clip being loaded.) Movie clip and button actions execute when the event specified by the handler occurs. You can attach more than one handler to an object if you want actions to execute when different events happen. For more information, see Chapter 3, Creating interaction with ActionScript: Overview . Several onClipEvent handlers attached to a movie clip on the Stage  
  96.  
  97. <url>html/01_understanding8.html</url>
  98. <title>ActionScript terminology</title> ActionScript terminology Understanding ActionScript > ActionScript terminology Like any scripting language, ActionScript uses specific terminology according to specific rules of syntax. The following list provides an introduction to important ActionScript terms in alphabetical order. These terms and the syntax that governs them are discussed in more detail in Writing scripts with ActionScript: Overview . Actions are statements that instruct a movie to do something while it is playing. For example, gotoAndStop sends the playhead to a specific frame or label. In this book, the terms action and statement are interchangeable. Arguments , also called parameters, are placeholders that let you pass values to functions. For example, the following function, called welcome , uses two values it receives in the arguments firstName and hobby : function welcome(firstName, hobby) { welcomeText = "Hello, " + firstName + "I see you enjoy " + hobby; } Classes are data types that you can create to define a new type of object. To define a class of object, you create a constructor function. Constants are elements that don't change. For example, the constant TAB always has the same meaning. Constants are useful for comparing values. Constructors are functions that you use to define the properties and methods of a class. For example, the following code creates a new Circle class by creating a constructor function called Circle : function Circle(x, y, radius){ this.x = x; this.y = y; this.radius = radius; } Data types are a set of values and the operations that can be performed on them. String, number, true and false (Boolean) values, object, and movie clip are the ActionScript data types. For more details on these language elements, see About data types . Events are actions that occur while a movie is playing. For example, different events are generated when a movie clip loads, the playhead enters a frame, the user clicks a button or movie clip, or the user types at the keyboard. Expressions are any parts of a statement that produce a value. For example, 2 + 2 is an expression. Functions are blocks of reusable code that can be passed arguments (parameters) and can return a value. For example, the getProperty function is passed the name of a property and the instance name of a movie clip, and it returns the value of the property. The getVersion function returns the version of the Flash Player currently playing the movie. Handlers are special actions that "handle" or manage an event such as mouseDown or load . For example, on (onMouseEvent) and onClipEvent are ActionScript handlers. Identifiers are names used to indicate a variable, property, object, function, or method. The first character must be a letter, underscore(_), or dollar sign($). Each subsequent character must be a letter, number, underscore(_), or dollar sign($). For example, firstName is the name of a variable. Instances are objects that belong to a certain class. Each instance of a class contains all the properties and methods of that class. All movie clips are instances with properties (for example, _alpha , and _visible ) and methods (for example, gotoAndPlay , and getURL ) of the MovieClip class. Instance names are unique names that allow you to target movie clip instances in scripts. For example, a master symbol in the Library could be called counter and the two instances of that symbol in the movie could have the instance names scorePlayer1 and scorePlayer2 . The following code sets a variable called score inside each movie clip instance by using instance names: _root.scorePlayer1.score += 1 _root.scorePlayer2.score -= 1 Keywords are reserved words that have special meaning. For example, var is a keyword used to declare local variables. Methods are functions assigned to an object. After a function is assigned, it can be called as a method of that object. For example, in the following code, clear becomes a method of the controller object: function Reset(){ x_pos = 0; x_pos = 0; } controller.clear = Reset; controller.clear(); Objects are collections of properties; each object has its own name and value. Objects allow you to access a certain type of information. For example, the predefined Date object provides information from the system clock. Operators are terms that calculate a new value from one or more values. For example, the addition ( + ) operator adds two or more values together to produce a new value. Target paths are hierarchical addresses of movie clip instance names, variables, and objects in a movie. You can name a movie clip instance in the Instance panel. The main Timeline always has the name _root . You can use a target path to direct an action at a movie clip or to get or set the value of a variable. For example, the following statement is the target path to the variable volume inside the movie clip stereoControl: _root.stereoControl.volume Properties are attributes that define an object. For example, _visible is a property of all movie clips that defines whether the movie clip is visible or hidden. Variables are identifiers that hold values of any data type. Variables can be created, changed, and updated. The values they store can be retrieved for use in scripts. In the following example, the identifiers on the left side of the equal signs are variables: x = 5; name = "Lolo"; customer.address = "66 7th Street"; c = new Color(mcinstanceName);
  99.  
  100. <url>html/01_understanding9.html</url>
  101. <title>Deconstructing a sample script</title> Deconstructing a sample script Understanding ActionScript > Deconstructing a sample script In this sample movie, when a user drags the bug to the bug zapper, the bug turns black and falls and the bug zapper flashes. The movie is one frame long and contains two objects, the bug movie clip instance and the zapper movie clip instance. Each movie clip also contains one frame. The bug and zapper movie clip instances on the Stage in frame 1   There is only one script in the movie; it's attached to the bug instance, as in the Object Actions panel below: The Object Actions panel with the script attached to the bug instance   Both objects have to be movie clips so you can give them instance names in the Instance panel and manipulate them with ActionScript. The bug's instance name is bug and the zapper's instance name is zapper . In the script the bug is referred to as this because the script is attached to the bug and the reserved word this refers to the object that calls it. There are two onClipEvent handlers with two different events: load and enterFrame . The actions in the onClipEvent(load) statement only execute once, when the movie loads. The actions in the onClipEvent(enterFrame) statement execute every time the playhead enters a frame. Even in a one-frame movie, the playhead still enters that frame repeatedly and the script executes repeatedly. The following actions occur within each onClipEvent handler: onClipEvent(load)  A startDrag action makes the bug movie clip draggable. An instance of the Color object is created with the new operator and the Color constructor function, Color , and assigned to the variable zap : onClipEvent (load) { startDrag (this, true); zap = new Color(this); } onClipEvent(enterFrame)  A conditional if statement evaluates a hitTest action to check whether the bug instance ( this ) is touching the bug zapper instance ( _root.zapper ). There are two possible outcomes of the evaluation, true or false : onClipEvent (enterFrame) { if (this.hitTest(_root.zapper)) { zap.setRGB(0); setProperty (_target, _y, _y+50); setProperty (_root.zapper, _alpha, 50); stopDrag (); } else { setProperty (_root.zapper, _alpha, 100); } } If the hitTest action returns true , the zap object created by the load event is used to set the bug's color to black. The bug's y property ( _y ) is set to itself plus 50 so that the bug falls. The zapper's transparency ( _alpha ) is set to 50 so that it dims . The stopDrag action stops the bug from being draggable. If the hitTest action returns false , the action following the else statement runs and the bug zapper's _alpha value is set to 100 . This makes the bug zapper appear to flash as its _alpha value goes from an initial state (100) to a zapped state (50) and back to an initial state. The hitTest action returns false and the else statements execute after the bug has been zapped and fallen.
  102.  
  103. <url>html/02_writing_scripts1.html</url>
  104. <title>Writing scripts with ActionScript: Overview</title> Writing scripts with ActionScript: Overview Writing Scripts with ActionScript > Writing scripts with ActionScript: Overview When you create scripts in ActionScript, you can choose the level of detail you want to use. To use simple actions, you can use the Actions panel in Normal Mode and build scripts by choosing options from menus and lists. However, if you want to use ActionScript to write more powerful scripts, you must understand how ActionScript works as a language. Like other scripting languages, ActionScript consists of components, such as predefined objects and functions, and it allows you to create your own objects and functions. ActionScript follows its own rules of syntax, reserves keywords, provides operators, and allows you to use variables to store and retrieve information. ActionScript's syntax and style closely resemble that of JavaScript. Flash 5 performs conversions on ActionScript written in any previous version of Flash.
  105.  
  106. <url>html/02_writing_scripts10.html</url>
  107. <title>Using predefined objects</title> Using predefined objects Writing Scripts with ActionScript > Using predefined objects You can use Flash's predefined objects to access certain kinds of information. Most predefined objects have methods (functions assigned to an object) that you can call to return a value or perform an action. For example, the Date object returns information from the system clock and the Sound object lets you control sound elements in your movie. Some predefined objects have properties whose values you can read. For example, the Key object has constant values that represent keys on the keyboard. Each object has its own characteristics and abilities that can be used in your movie. The following are Flash's predefined objects: Array Boolean Color Date Key Math MovieClip Number Object Selection Sound String XML XMLSocket Movie clip instances are represented as objects in ActionScript. You can call predefined movie clip methods just as you would call the methods of any other ActionScript object. For detailed information on each object, see its entry in ActionScript dictionary: Overview.   Creating an object There are two ways to create an object: the new operator and the object initializer operator ( {} ). You can use the new operator to create an object from a predefined object class, or from a custom defined object class. You can use the object initializer operator ( {} ) to create an object of generic type Object. To use the new operator to create an object, you need to use it with a constructor function. (A constructor function is simply a function whose sole purpose is to create a certain type of object.) ActionScript's predefined objects are essentially prewritten constructor functions. The new object instantiates, or creates, a copy of the object and assigns it all the properties and methods of that object. This is similar to dragging a movie clip from the Library to the Stage in a movie. For example, the following statements instantiate a Date object: currentDate = new Date(); You can access the methods of some predefined objects without instantiating them. For example, the following statement calls the Math object method random : Math.random(); Each object that requires a constructor function has a corresponding element in the Actions panel toolbox; for example, new Color , new Date , new String , and so on. To create an object with the new operator in Normal Mode: 1 Choose setVariable 2 Enter an identifier in the Name field. 3 Enter new Object , new Color , and so on in the Value field. Enter any arguments required by the constructor function in parentheses. 4 Check the Expression box of the Value field. If you don't check the Expression box, the entire value will be a string literal. In the following code, the object c is created from the constructor Color: c = new Color(this); Note: An object name is a variable with the object data type assigned to it. To access a method in Normal Mode: 1 Select the evaluate action. 2 Enter the name of the object in the Expression field. 3 Enter a property of the object in the Expression field. To use the object initializer operator ( {} ) in Normal Mode: 1 Select the setVariable action. 2 Enter name in the Variable field; this is the name of the new object. 3 Enter the property name and value pairs separated by a colon inside the object initializer operator ( {} ). For example, in this statement the property names are radius and area and their values are 5 and the value of an expression: myCircle = {radius: 5, area:(pi * radius * radius)}; The parentheses cause the expression to evaluate. The returned value is the value of the variable area . You can also nest array and object initializers, as in this statement: newObject = {name: "John Smith", projects: ["Flash", "Dreamweaver"]}; For detailed information on each object, see its entry in ActionScript dictionary: Overview.   Accessing object properties Use the dot ( . ) operator to access the value of properties in an object. The name of the object goes on the left side of the dot, and the name of the property goes on the right side. For example, in the following statement, myObject is the object and name is the property: myObject.name To assign a value to a property in Normal Mode, use the setVariable action: myObject.name = "Allen"; To change the value of a property, assign a new value as shown here: myObject.name = "Homer"; You can also use the array access operator ( [] ) to access the properties of an object. See Dot and array access operators .   Calling object methods You can call an object's method by using the dot operator followed by the method. For example, the following example calls the setVolume method of the Sound object: s = new Sound(this); s.setVolume(50); To call the method of a predefined object in Normal Mode, use the evaluate action.   Using the MovieClip object You can use the methods of the predefined MovieClip object to control movie clip symbol instances on the Stage. The following example tells the instance dateCounter to play: dateCounter.play(); For detailed information on the MovieClip object, see its entry in ActionScript dictionary: Overview.   Using the Array object The Array object is a commonly used predefined ActionScript object that stores its data in numbered properties instead of named properties. An array element's name is called an index . This is useful for storing and retrieving certain types of information such as lists of students or a sequence of moves in a game. You can assign elements of the Array object just as you would the property of any object: move[1] = "a2a4"; move[2] = "h7h5"; move[3] = "b1c3"; ... move[100] = "e3e4"; To access the second element of the array, use the expression move[ 2 ] . The Array object has a predefined length property that is the value of the number of elements in the array. When an element of the Array object is assigned and the element's index is a positive integer such that index >= length , length is automatically updated to index + 1 .
  108.  
  109. <url>html/02_writing_scripts11.html</url>
  110. <title>Using custom objects</title> Using custom objects Writing Scripts with ActionScript > Using custom objects You can create custom objects to organize information in your scripts for easier storage and access by defining an object's properties and methods. After you create a master object or "class," you can use or "instantiate" copies (that is, instances) of that object in a movie. This allows you to reuse code and conserve file size. An object is a complex data type containing zero or more properties. Each property, like a variable, has a name and a value. Properties are attached to the object and contain values that can be changed and retrieved. These values can be of any data type: string, number, Boolean, object, movie clip, or undefined . The following properties are of various data types: customer.name = "Jane Doe"; customer.age = 30; customer.member = true; customer.account.currentRecord = 000609; customer.mcInstanceName._visible = true; The property of an object can also be an object. In line 4 of the previous example, account is a property of the object customer and currentRecord is a property of the object account . The data type of the currentRecord property is number.   Creating an object You can use the new operator to create an object from a constructor function. A constructor function is always given the same name as the type of object it is creating. For example, a constructor that creates an account object would be called Account . The following statement creates a new object from the function called MyConstructorFunction : new MyConstructorFunction (argument1, argument2, ... argumentN); When MyConstructorFunction is called, Flash passes it the hidden argument this , which is a reference to the object that the MyConstructorFunction is creating. When you define a constructor, this allows you to refer to the objects that the constructor will create. For example, the following is a constructor function that creates a circle: function Circle(radius) { this.radius = radius; this.area = Math.PI * radius * radius; } Constructor functions are commonly used to fill in the methods of an object. function Area() { this.circleArea = MAth.PI * radius * radius; } To use an object in a script, you must assign it to a variable. To create a new circle object with the radius 5, use the new operator to create the object and assign it to the local variable myCircle : var myCircle = new Circle(5); Note: Objects have the same scope as the variable to which they are assigned. See Scoping a variable .   Creating inheritance All functions have a prototype property that is created automatically when the function is defined. When you use a constructor function to create a new object, all the properties and methods of the constructor's prototype property become properties and methods of the __proto__ property of the new object. The prototype property indicates the default property values for objects created with that function. Passing values using the __proto__ and prototype properties is called inheritance. Inheritance proceeds according to a definite hierarchy. When you call an object's property or method, ActionScript looks at the object to see if such an element exists. If it doesn't exist, ActionScript looks at the object's __proto__ property for the information ( object.__proto__ ). If the called property is not a property of the object's __proto__ object, ActionScript looks at object . __proto__ . __proto__ . It's common practice to attach methods to an object by assigning them to the object's prototype property. The following steps describe how to define a sample method: 1 Define the constructor function Circle , as follows: function Circle(radius) { this.radius = radius; } 2 Define the area method of the Circle object. The area method will calculate the area of the circle. You can use a function literal to define the area method and set the area property of the circle's prototype object, as follows: Circle.prototype.area = function () { return Math.PI * this.radius * this.radius; } 3 Create an instance of the Circle object, as follows: var myCircle = new Circle(4); 4 Call the area method of the new myCircle object, as follows: var myCircleArea = myCircle.area() ActionScript searches the myCircle object for the area method. Since the object doesn't have an area method , its prototype object Circle.prototype is searched for the area method. ActionScript finds it and calls it. You can also attach a method to an object by attaching the method to every individual instance of the object, as in this example: function Circle(radius) { this.radius = radius; this.area = function() { return Math.PI * this.radius * this.radius; } } This technique is not recommended. Using the prototype object is more efficient, because only one definition of area is necessary, and that definition is automatically copied into all instances created by the Circle function. The prototype property is supported by Flash Player version 5 and later. For more information, see ActionScript dictionary: Overview.
  111.  
  112. <url>html/02_writing_scripts12.html</url>
  113. <title>Opening Flash 4 files</title> Opening Flash 4 files Writing Scripts with ActionScript > Opening Flash 4 files ActionScript has changed considerably with the release of Flash 5. It is now an object-oriented language with multiple data types and dot syntax. Flash 4 ActionScript only had one true data type: string. It used different types of operators in expressions to indicate whether the value should be treated as a string or as a number. In Flash 5, you can use one set of operators on all data types. When you use Flash 5 to open a file that was created in Flash 4, Flash automatically converts ActionScript expressions to make them compatible with the new Flash 5 syntax. You'll see the following data type and operator conversions in your ActionScript code: The = operator in Flash 4 was used for numeric equality. In Flash 5, == is the equality operator and = is the assignment operator. Any = operators in Flash 4 files are automatically converted to == . Flash automatically performs type conversions to ensure that operators behave as expected. Because of the introduction of multiple data types, the following operators have new meanings: +, ==, !=, <>, <, >, >=, <= In Flash 4 ActionScript, these operators were always numeric operators. In Flash 5, they behave differently depending on the data types of the operands. To prevent any semantic differences in imported files, the Number function is inserted around all operands to these operators. (Constant numbers are already obviously numbers, so they are not enclosed in Number ). In Flash 4, the escape sequence \n generated a carriage return character (ASCII 13). In Flash 5, to comply with the ECMA-262 standard, \n generates a line-feed character (ASCII 10). An \n sequence in Flash 4 FLA files is automatically converted to \r . The & operator in Flash 4 was used for string addition. In Flash 5, & is the bitwise AND operator. The string addition operator is now called add . Any & operators in Flash 4 files are automatically converted to add operators. Many functions in Flash 4 did not require closing parentheses, for example, Get Timer , Set Variable , Stop , and Play . To create consistent syntax, the Flash 5 getTimer function and all actions now require closing parentheses. These parentheses are automatically added during the conversion. When the getProperty function is executed on a movie clip that doesn't exist, it returns the value undefined , not 0, in Flash 5. And undefined == 0 is false in Flash 5 ActionScript. Flash fixes this problem when converting Flash 4 files by introducing Number functions in equality comparisons. In the following example, Number forces undefined to be converted to 0 so the comparison will succeed: getProperty("clip", _width) == 0 Number(getProperty("clip", _width)) == Number(0) Note: If you used any Flash 5 keywords as variable names in your Flash 4 ActionScript, the syntax will return an error in Flash 5. To fix this, rename your variables in all locations. See Keywords .
  114.  
  115. <url>html/02_writing_scripts13.html</url>
  116. <title>Using Flash 5 to create Flash 4 content</title> Using Flash 5 to create Flash 4 content Writing Scripts with ActionScript > Using Flash 5 to create Flash 4 content If you are using Flash 5 to create content for the Flash 4 Player (by exporting as Flash 4), you won't be able to take advantage of all the new features present in Flash 5 ActionScript. However, many new ActionScript features are still available. Flash 4 ActionScript has only one basic primitive data type which is used for both numeric and string manipulation. When you author a movie for the Flash 4 Player, you need to use the deprecated string operators located in the String Operators category in the toolbox. You can use the following Flash 5 features when you export to the Flash 4 SWF file format: The array and object access operator ( [] ). The dot operator ( . ). Logical operators, assignment operators, and pre-increment and post-increment/decrement operators. The modulo operator( % ), all methods and properties of the Math object. These operators and functions are not supported natively by the Flash 4 Player. Flash 5 must export them as series approximations. This means that the results are only approximate. In addition, due to the inclusion of series approximations in the SWF file, these functions take up more room in Flash 4 SWF files than they do in Flash 5 SWF files. The for , while , do..while , break , and continue actions. The print and printAsBitmap actions. The following Flash 5 features can't be used in movies exported to the Flash 4 SWF file format: Custom functions XML support Local variables Predefined objects (except Math) Movie clip actions Multiple data types eval with dot syntax (for example, eval("_root.movieclip.variable") ) return new delete typeof for..in keycode targetPath escape globalToLocal and localToGlobal hitTest isFinite and inNaN parseFloat and parseInt unescape _xmouse and _ymouse _quality
  117.  
  118. <url>html/02_writing_scripts2.html</url>
  119. <title>Using ActionScript's syntax</title> Using ActionScript's syntax Writing Scripts with ActionScript > Using ActionScript's syntax ActionScript has rules of grammar and punctuation that determine which characters and words are used to create meaning and in which order they can be written. For example, in English, a period ends a sentence. In ActionScript, a semicolon ends a statement. The following are general rules that apply to all ActionScript. Most ActionScript terms also have their own individual requirements; for the rules for a specific term, see the its entry in ActionScript dictionary: Overview.   Dot syntax In ActionScript, a dot (.) is used to indicate the properties or methods related to an object or movie clip. It is also used to identify the target path to a movie clip or variable. A dot syntax expression begins with the name of the object or movie clip followed by a dot, and ends with the property, method, or variable you want to specify. For example, the _x movie clip property indicates a movie clip's x axis position on the Stage. The expression ballMC._x refers to the _x property of the movie clip instance ballMC . As another example, submit is a variable set in the movie clip form which is nested inside the movie clip shoppingCart . The expression shoppingCart . form.submit = true sets the submit variable of the instance form to true . Expressing a method of an object or movie clip follows the same pattern. For example, the play method of the ballMC instance moves the playhead in the Timeline of ballMC , as in the following statement: ballMC.play(); Dot syntax also uses two special aliases, _root and _parent . The alias _root refers to the main Timeline. You can use the _root alias to create an absolute target path. For example, the following statement calls the function buildGameBoard in the movie clip functions on the main Timeline: _root.functions.buildGameBoard(); You can use the alias _parent to refer to a movie clip in which the current movie clip is nested. You can use _parent to create a relative target path. For example, if the movie clip dog is nested inside the movie clip animal , the following statement on the instance dog tells animal to stop: _parent.stop(); See Working with movie clips: Overview .   Slash syntax Slash syntax was used in Flash 3 and 4 to indicate the target path of a movie clip or variable. This syntax is still supported by the Flash 5 Player, but its use is not recommended. In slash syntax, slashes are used instead of dots to indicate the path to a movie clip or variable. To indicate a variable, you precede the variable with a colon as in the following: myMovieClip/childMovieClip:myVariable You can write the same target path in dot syntax, as in the following: myMovieClip.childMovieClip.myVariable Slash syntax was most commonly used with the tellTarget action, whose use is also no longer recommended. Note: The with action is now preferred over tellTarget because it is more compatible with dot syntax. For more information, see their individual entries in the ActionScript Dictionary.   Curly braces ActionScript statements are grouped together into blocks with curly braces ( { }) , as in the following script: on(release) { myDate = new Date(); currentMonth = myDate.getMonth(); } See Using actions .   Semicolons An ActionScript statement is terminated with a semicolon, but if you omit the terminating semicolon, Flash will still compile your script successfully. For example, the following statements are terminated with semicolons: column = passedDate.getDay(); row = 0; The same statements could be written without the terminating semicolons: column = passedDate.getDay() row = 0   Parentheses When you define a function, place any arguments inside parentheses: function myFunction ( name, age, reader ){ ... } When you call a function, include any arguments passed to the function in parentheses, as shown here: myFunction ("Steve", 10, true); You can also use parentheses to override ActionScript's order of precedence or to make your ActionScript statements easier to read. See Operator precedence . You also use parentheses to evaluate an expression on the left side of a dot in dot syntax. For example, in the following statement, the parentheses cause new color(this) to evaluate and create a new color object: onClipEvent(enterFrame) { (new Color(this)).setRGB(0xffffff)); } If you didn't use parentheses, you would need to add a statement to the code to evaluate it: onClipEvent(enterFrame) { myColor = new Color(this); myColor.setRGB(0xffffff); }   Uppercase and lowercase letters Only keywords in ActionScript are case sensitive; with the rest of ActionScript, you can use uppercase and lowercase letters however you want. For example, the following statements are equivalent: cat.hilite = true; CAT.hilite = true; However, it's a good habit to follow consistent capitalization conventions, such as those used in this book, to make it is easier to identify names of functions and variables when reading ActionScript code. If you don't use correct capitalization with keywords, your script will have errors. When Colored Syntax is turned on in the Actions panel, keywords written with the correct capitalization are blue. For more information, see Keywords and Highlighting and checking syntax .   Comments In the Actions panel, use the comment statement to add notes to a frame or button action when you want to keep track of what you intended an action to do. Comments are also useful for passing information to other developers if you work in a collaborative environment or are providing samples. When you choose the comment action, the characters // are inserted into the script. Even a simple script is easier to understand if you make notes as you create it: on(release) { // create new Date object myDate = new Date(); currentMonth = myDate.getMonth(); // convert month number to month name monthName = calcMonth(currentMonth); year = myDate.getFullYear(); currentDate = myDate.getDat (); } Comments appear in pink in the Script window. They can be any length without affecting the size of the exported file, and they do not need to follow rules for ActionScript syntax or keywords.   Keywords ActionScript reserves words for specific use within the language, so you can't use them as variable, function, or label names. The following table lists all ActionScript keywords: break for new var continue function return void delete if this while else in typeof with For more information about a specific keyword, see its entry in the ActionScript Dictionary.   Constants A constant is a property whose value never changes. Constants are listed in the Actions toolbox and in the ActionScript dictionary: Overview in all uppercase letters. For example, the constants BACKSPACE , ENTER , QUOTE , RETURN , SPACE , and TAB are properties of the Key object and refer to keyboard keys. To test whether the user is pressing the Enter key, use the following statement: if(keycode() == Key.ENTER) { alert = "Are you ready to play?" controlMC.gotoAndStop(5); }
  120.  
  121. <url>html/02_writing_scripts3.html</url>
  122. <title>About data types</title> About data types Writing Scripts with ActionScript > About data types A data type describes the kind of information a variable or ActionScript element can hold. There are two kinds of data types: primitive and reference. The primitive data types—string, number, and Boolean—have a constant value and, therefore, can hold the actual value of the element they represent. The reference data types—movie clip and object—have values that can change and, therefore, contain references to the actual value of the element. Variables containing primitive data types behave differently in certain situations than those containing reference types. See Using variables in a script . Each data type has its own rules and is listed here. References are included for data types that are discussed in more detail.   String A string is a sequence of characters such as letters, numbers, and punctuation marks. You enter strings in an ActionScript statement by enclosing them in single or double quotation marks. Strings are treated as characters instead of as variables. For example, in the following statement, "L7" is a string: favoriteBand = "L7"; You can use the addition (+ ) operator to concatenate , or join, two strings. ActionScript treats spaces at the beginning or end of a string as a literal part of the string. The following expression includes a space after the comma: greeting = "Welcome," + firstName; Although ActionScript does not distinguish between uppercase and lowercase in references to variables, instance names, and frame labels, literal strings are case sensitive. For example, the following two statements place different text into the specified text field variables, because "Hello" and "HELLO" are literal strings. invoice.display = "Hello"; invoice.display = "HELLO"; To include a quotation mark in a string, precede it with a backslash character (\). This is called "escaping" a character. There are other characters that cannot be represented in ActionScript except by special escape sequences. The following table provides all the ActionScript escape characters: Escape sequence Character \b Backspace character (ASCII 8) \f Form-feed character (ASCII 12) \n Line-feed character (ASCII 10) \r Carriage return character (ASCII 13) \t Tab character (ASCII 9) \" Double quotation mark \' Single quotation mark \\ Backslash \000 - \377 A byte specified in octal \x00 - \xFF A byte specified in hexadecimal \u0000 - \uFFFF A 16-bit Unicode character specified in hexadecimal   Number The number data type is a double-precision floating-point number. You can manipulate numbers using the arithmetic operators addition (+), subtraction (-), multiplication (*), division (/), modulo (%), increment (++), and decrement (--). You can also use methods of the predefined Math object to manipulate numbers. The following example uses the sqrt (square root) method to return the square root of the number 100: Math.sqrt(100); See Numeric operators .   Boolean A Boolean value is one that is either true or false . ActionScript also converts the values true and false to 1 and 0 when appropriate. Boolean values are most often used with logical operators in ActionScript statements that make comparisons to control the flow of a script. For example, in the following script, the movie plays if the variable password is true : onClipEvent(enterFrame) { if ((userName == true) && (password == true)){ play(); } } See Using "if" statements and Logical operators .   Object An object is a collection of properties. Each property has a name and a value. The value of a property can be any Flash data type, even the object data type. This allows you to arrange objects inside each other, or "nest" them. To specify objects and their properties, you use the dot (.) operator. For example, in the following code, hoursWorked is a property of weeklyStats , which is a property of employee : employee.weeklyStats.hoursWorked You can use ActionScript's predefined objects to access and manipulate specific kinds of information. For example, the Math object has methods that perform mathematical operations on numbers you pass to them. This example uses the sqrt method: squareRoot = Math.sqrt(100); The ActionScript MovieClip object has methods that let you control movie clip symbol instances on the Stage. This example uses the play and nextFrame methods: mcInstanceName.play(); mc2InstanceName.nextFrame(); You can also create your own objects so that you can organize information in your movie. To add interactivity to a movie with ActionScript, you'll need many different pieces of information: for example, you might need a user's name, the speed of a ball, the names of items in a shopping cart, the number of frames loaded, the user's zip code, and which key was pressed last. Creating custom objects allows you to organize this information into groups, simplify your scripting, and reuse your scripts. For more information, see Using custom objects .   Movie clip Movie clips are symbols that can play animation in a Flash movie. They are the only data type that refers to a graphical element. The movie clip data type allows you to control movie clip symbols using the methods of the MovieClip object. You call the methods using the dot (.) operator, as shown here: myClip.startDrag(true); parentClip.childClip.getURL( "http://www.macromedia.com/support/" + product);
  123.  
  124. <url>html/02_writing_scripts4.html</url>
  125. <title>About variables</title> About variables Writing Scripts with ActionScript > About variables A variable is a container that holds information. The container itself is always the same, but the contents can change. By changing the value of a variable as the movie plays, you can record and save information about what the user has done, record values that change as the movie plays, or evaluate whether some condition is true or false. It's a good idea always to assign a variable a known value the first time you define the variable. This is known as initializing a variable and is often done in the first frame of the movie. Initializing variables makes it easier to track and compare the variable's value as the movie plays. Variables can hold any type of data: number, string, Boolean, object, or movie clip. The type of data a variable contains affects how the variable's value changes when it is assigned in a script. Typical types of information you can store in a variable include a URL, a user's name, the result of a mathematical operation, the number of times an event occurred, or whether a button has been clicked. Each movie and movie clip instance has its own set of variables, with each variable having its own value independent of variables in other movies or movie clips.   Naming a variable A variable's name must follow these rules: It must be an identifier. It cannot be a keyword or a Boolean literal ( true or false ). It must be unique within its scope. (See Scoping a variable .)   Typing a variable In Flash, you do not have to explicitly define a variable as holding either a number, a string, or other data type. Flash determines the data type of a variable when the variable is assigned: x = 3; In the expression x = 3 , Flash evaluates the element on the right side of the operator and determines that it is of type number. A later assignment may change the type of x ; for example, x = "hello" changes the type of x to a string. A variable that hasn't been assigned a value has a type of undefined . ActionScript converts data types automatically when an expression requires it. For example, when you pass a value to the trace action, trace automatically converts the value to a string and sends it to the Output window. In expressions with operators, ActionScript converts data types as needed; for example, when used with a string, the + operator expects the other operand to be a string: "Next in line, number " + 7 ActionScript converts the number 7 to the string "7" and adds it to the end of the first string, resulting in the following string: "Next in line, number 7" When you debug scripts, it's often useful to determine the data type of an expression or variable to understand why it is behaving a certain way. You can do this with the typeof operator, as in this example: trace(typeof( variableName )); To convert a string to a numerical value, use the Number function. To convert a numerical value to a string, use the String function. See their individual entries in ActionScript dictionary: Overview.   Scoping a variable A variable's "scope" refers to the area in which the variable is known and can be referenced. Variables in ActionScript can be either global or local. A global variable is shared among all Timelines; a local variable is only available within its own block of code (between the curly braces). You can use the var statement to declare a local variable inside a script. For example, the variables i and j are often used as loop counters. In the following example, i is used as a local variable; it only exists inside the function makeDays : function makeDays(){ var i for( i = 0; i < monthArray[month]; i++ ) { _root.Days.attachMovie( "DayDisplay", i, i + 2000 ); _root.Days[i].num = i + 1; _root.Days[i]._x = column * _root.Days[i]._width; _root.Days[i]._y = row * _root.Days[i]._height; column = column + 1; if (column == 7 ) { column = 0; row = row + 1; } } } Local variables can also help prevent name collisions, which can cause errors in your movie. For example, if you use name as a local variable, you could use it to store a user name in one context and a movie clip instance name in another; because these variables would run in separate scopes, there would be no collision. It's good practice to use local variables in the body of a function so that the function can act as an independent piece of code. A local variable is only changeable within its own block of code. If an expression in a function uses a global variable, something outside the function could change its value, which would change the function.   Variable declaration To declare global variables, use the setVariables action or the assignment (=) operator. Both methods achieve the same results. To declare local variables, use the var statement inside the body of a function. Local variables are scoped to the block, and expire at the end of the block. Local variables not declared within a block expire at the end of their script. Note: The call action also creates a new local variable scope for the script it calls. When the called script exits, this local variable scope disappears. However, this is not recommended because the call action has been replaced by the with action which is more compatible with dot syntax. To test the value of a variable, use the trace action to send the value to the Output window. For example, trace(hoursWorked) sends the value of the variable hoursWorked to the Output window in test-movie mode. You can also check and set the variable values in the Debugger in test-movie mode. For more information, see Troubleshooting ActionScript: Overview .   Using variables in a script You must declare a variable in a script before you can use it in an expression. If you use an undeclared variable, as in the following example, the variable's value will be undefined and your script will generate an error: getURL(myWebSite); myWebSite = "http://www.shrimpmeat.net"; The statement declaring the variable myWebSite must come first so that the variable in the getURL action can be replaced with a value. You can change the value of a variable many times in a script. The type of data that the variable contains affects how and when the variable changes. Primitive data types, such as strings and numbers, are passed by value. This means that the actual content of the variable is passed to the variable. In the following example, x is set to 15 and that value is copied into y . When x is changed to 30, the value of y remains 15 because y doesn't look to x for its value; it contains the value of x that it was passed. var x = 15; var y = x; var x = 30; As another example, the variable in contains a primitive value, 9, so the actual value is passed to the sqrt function and the returned value is 3: function sqrt(x){ return x * x; } var in = 9; var out = sqr(in); The value of the variable in does not change. The object data type can contain such a large and complex amount of information that a variable with this type doesn't hold the actual value; it holds a reference to the value. This reference is like an alias that points to the contents of the variable. When the variable needs to know its value, the reference asks for the contents and returns the answer without transferring the value to the variable. The following is an example of passing by reference: var myArray = ["tom", "dick"]; var newArray = myArray; myArray[1] = "jack"; trace(newArray); The above code creates an Array object called myArray that has two elements. The variable newArray is created and passed a reference to myArray . When the second element of myArray is changed, it affects every variable with a reference to it. The trace action would send ["tom", "jack"] to the Output window. In the next example, myArray contains an Array object, so it is passed to function zeroArray by reference. The zeroArray function changes the content of the array in myArray . function zeroArray (array){ var i; for (i=0; i < array.length; i++) { array[i] = 0; } } var myArray = new Array(); myArray[0] = 1; myArray[1] = 2; myArray[2] = 3; var out = zeroArray(myArray) The function zeroArray accepts an Array object as an argument and sets all the elements of that array to 0. It can modify the array because the array is passed by reference. References to all objects other than movie clips are called hard references because if an object is referenced, it cannot be deleted. A reference to a movie clip is a special kind of reference called a soft reference . Soft references do not force the referenced object to exist. If a movie clip is destroyed with an action such as removeMovieClip , any reference to it will no longer work.
  126.  
  127. <url>html/02_writing_scripts5.html</url>
  128. <title>Using operators to manipulate values in expressions</title> Using operators to manipulate values in expressions Writing Scripts with ActionScript > Using operators to manipulate values in expressions An expression is any statement that Flash can evaluate that will return a value. You can create an expression by combining operators and values, or by calling a function. When you write an expression in the Actions panel in Normal Mode, make sure the Expression box is checked in the Parameters panel, otherwise the field will contain the literal value of a string. Check the Expression box next to a field to create an expression   Operators are characters that specify how to combine, compare, or modify the values of an expression. The elements that the operator performs on are called operands . For example, in the following statement, the + operator adds the value of a numeric literal to the value of the variable foo; foo and 3 are the operands: foo + 3 This topic describes general rules about common types of operators. For detailed information on each operator mentioned here, as well as special operators that don't fall into these categories, see ActionScript dictionary: Overview.   Operator precedence When two or more operators are used in the same statement, some operators take precedence over others. ActionScript follows a precise hierarchy to determine which operators to execute first. For example, multiplication is always performed before addition; however, items in parentheses take precedence over multiplication. So, without parentheses, ActionScript performs the multiplication in the following example first: total = 2 + 4 * 3; The result is 14. But when parentheses surround the addition operation, ActionScript performs the addition first: total = (2 + 4) * 3; The result is 18. For a table of all operators and their precedence, see Operator List .   Operator associativity When two or more operators share the same precedence, their associativity determines the order in which they are performed. Associativity can either be left-to-right or right-to-left. For example, the multiplication operator has an associativity of left-to-right; therefore, the following two statements are equivalent: total = 2 * 3 * 4; total = (2 * 3) * 4; For a table of all operators and their associativity, see Operator List .   Numeric operators Numeric operators add, subtract, multiply, divide, and perform other arithmetic operations. Parentheses and the minus sign are arithmetic operators. The following table lists ActionScript's numeric operators: Operator Operation performed + Addition * Multiplication / Division % Modulo - Subtraction ++ Increment -- Decrement   Comparison operators Comparison operators compare the values of expressions and return a Boolean value ( true or false ). These operators are most commonly used in loops and in conditional statements. In the following example, if variable score is 100 , a certain movie loads; otherwise, a different movie loads: if (score == 100){ loadMovie("winner.swf", 5); } else { loadMovie("loser.swf", 5); } The following table lists ActionScript's comparison operators: Operator Operation performed < Less than > Greater than <= Less than or equal >= Greater than or equal   String operators The + operator has a special effect when it operates on strings: it concatenates the two string operands. For example, the following statement adds: "Congratulations," to "Donna!" : "Congratulations, " + "Donna!" The result is "Congratulations, Donna!" If only one of the + operator's operands is a string, Flash converts the other operand to a string. The comparison operators > , >= , < , and <= also have a special effect when operating on strings. These operators compare two strings to determine which is first in alphabetical order. The comparison operators only compare strings if both operands are strings. If only one of the operands is a string, ActionScript converts both operands to numbers and performs a numeric comparison. Note: ActionScript's data typing in Flash 5 allows the same operators to be used on different types of data. It is no longer necessary to use the Flash 4 string operators (for example, eq , ge , and lt ) unless you are exporting as a Flash 4 movie.   Logical operators Logical operators compare Boolean ( true and false ) values and return a third Boolean value. For example, if both operands evaluate to true , the logical AND operator ( && ) returns true . If one or both of the operands evaluate to true , the logical OR operator ( || ) returns false . Logical operators are often used in conjunction with comparison operators to determine the condition of an if action. For example, in the following script, if both expressions are true , the if action will execute: if ((i > 10) && (_framesloaded > 50)){ play(); } The following table lists ActionScript's logical operators: Operator Operation performed && Logical AND || Logical OR ! Logical NOT   Bitwise operators Bitwise operators internally manipulate floating-point numbers to change them into 32-bit integers, which are easier to work with. The exact bitwise operation performed depends on the operator, but all bitwise operations evaluate each digit of a floating-point number separately to compute a new value. The following table lists ActionScript's bitwise operators: Operator Operation performed & Bitwise And | Bitwise Or ^ Bitwise Xor ~ Bitwise Not << Shift left >> Shift right >>> Shift right zero fill   Equality and assignment operators You can use the equality ( == ) operator to determine whether the values or identities of two operands are equal. This comparison returns a Boolean ( true or false ) value. If the operands are strings, numbers, or Boolean values, they are compared by value. If the operands are objects or arrays, they are compared by reference. You can use the assignment ( = ) operator to assign a value to a variable, as in the following: password = "Sk8tEr"; You can also use the assignment operator to assign multiple variables in the same expression. In the following statement, the value of b is assigned to the variables c, and d: a = b = c = d; You can also use compound assignment operators to combine operations. Compound operators perform on both operands and then assign that new value to the first operand. For example, the following two statements are equivalent: x += 15; x = x + 15; The following table lists ActionScript's equality and assignment operators: Operator Operation performed == Equality != Inequality = Assignment += Addition and assignment -= Subtraction and assignment *= Multiplication and assignment %= Modulo and assignment /= Division and assignment <<= Bitwise shift left and assignment >>= Bitwise shift right and assignment >>>= Shift right zero fill and assignment ^= Bitwise Xor and assignment |= Bitwise Or and assignment &= Bitwise And and assignment   Dot and array access operators You can use the dot operator ( . ) and the array access operator ( [] ) to access any predefined or custom ActionScript object properties, including those of a movie clip. The dot operator uses the name of an object on its left side and the name of a property or variable on its right side. The property or variable name can't be a string or a variable that evaluates to a string; it must be an identifier. The following are examples using the dot operator: year.month = "June"; year.month.day = 9; The dot operator and the array access operator perform the same role, but the dot operator takes an identifier as its property and the array access operator evaluates its contents to a name and then accesses the value of that named property. For example, the following two lines of code access the same variable velocity in the movie clip rocket : rocket.velocity; rocket["velocity"]; You can use the array access operator to dynamically set and retrieve instance names and variables. For example, in the following code, the expression inside the [] operator is evaluated and the result of the evaluation is used as the name of the variable to be retrieved from movie clip name : name["mc" + i ] If you are familiar with the Flash 4 ActionScript slash syntax, you may have done the same thing using the eval function, as in the following: eval("mc" & i); The array access operator can also be used on the left side of an assignment statement. This allows you to dynamically set instance, variable, and object names, as in the following example: name[index] = "Gary"; Again, this is equivalent to the following Flash 4 ActionScript slash syntax: Set Variable: "name:" & index = "Gary" The array access operator can also be nested with itself to simulate multidimensional arrays. chessboard[row][column] This is equivalent to the following slash syntax: eval("chessboard/" & row & ":" & column) Note: If you want to write ActionScript that is compatible with the Flash 4 Player, you can use the eval action with the add operator.
  129.  
  130. <url>html/02_writing_scripts6.html</url>
  131. <title>Using actions</title> Using actions Writing Scripts with ActionScript > Using actions Actions are ActionScript's statements, or commands. Multiple actions assigned to the same frame or object create a script. Actions can act independently of each other, as in the following statements: swapDepths("mc1", "mc2"); gotoAndPlay(15); You can also nest actions by using one action inside another; this allows actions to affect each other. In the following example, the if action tells the gotoAndPlay action when to execute: if (i >= 25) { gotoAndPlay(10); } Actions can move the playhead in the Timeline ( gotoAndPlay ), control the flow of a script by creating loops ( do while ) or conditional logic ( if ), or create new functions and variables ( function , setVariable ). The following table lists all ActionScript actions: Actions break evaluate include print stopDrag call for loadMovie printAsBitmap swapDepths comment for...in loadVariables removeMovieClip tellTarget continue fsCommand nextFrame nextScene return toggleHighQuality delete function on setVariable stopDrag do...while getURL onClipEvent setProperty trace duplicateMovieClip gotoAndPlay gotoAndStop play startDrag unloadMovie else if prevFrame stop var else if ifFrameLoaded prevScene stopAllSounds while For syntax and usage examples of each action, see individual entries in ActionScript dictionary: Overview. Note: In this help system, the ActionScript term action is synonymous with the JavaScript term statement .   Writing a target path To use an action to control a movie clip or loaded movie, you must specify its name and its address, called a target path . The following actions take one or more target paths as arguments: loadMovie loadVariables unloadMovie setProperty startDrag duplicateMovieClip removeMovieClip print printAsBitmap tellTarget For example, the loadMovie action takes the arguments URL , Location , and Variables . The URL is the location on the Web of the movie you want to load. The Location is the target path into which the movie will be loaded. loadMovie( URL , Location , Variables ); Note: The Variables argument is not required for this example. The following statement loads the URL http://www.mySite.com/myMovie.swf into the instance bar on the main Timeline, _root; _root.bar is the target path; loadMovie("http://www.mySite.com/myMovie.swf", _root.bar); In ActionScript you identify a movie clip by its instance name. For example, in the following statement, the _alpha property of the movie clip named star is set to 50% visibility: star._alpha = 50; To give a movie clip an instance name: 1 Select the movie clip on the Stage. 2 Choose Window > Panels > Instance. 3 Enter an instance name in the Name field. To identify a loaded movie: Use _levelX where X is the level number specified in the loadMovie action that loaded the movie. For example, a movie loaded into level 5 has the instance name _level5 . In the following example, a movie is loaded into level 5 and its visibility is set to false: onClipEvent(load) { loadMovie("myMovie.swf", 5); } onClipEvent(enterFrame) { _level5._visible = false; } To enter a movie's target path: Click the Insert Target Path button in the Actions panel, and select a movie clip from the list that appears. For more information about writing target paths, see Working with movie clips: Overview .
  132.  
  133. <url>html/02_writing_scripts7.html</url>
  134. <title>Controlling flow in scripts</title> Controlling flow in scripts Writing Scripts with ActionScript > Controlling flow in scripts ActionScript uses if , for , while , do...while , and for...in actions to perform an action depending on whether a condition exists.   Using "if" statements Statements that check whether a condition is true or false begin with the term if . If the condition exists, ActionScript executes the statement that follows. If the condition doesn't exist, ActionScript skips to the next statement outside the block of code. To optimize your code's performance, check for the most likely conditions first. The following statements test several conditions. The term else if specifies alternative tests to perform if previous conditions are false. if ((password == null) || (email == null)){ gotoAndStop("reject"); } else { gotoAndPlay("startMovie"); }   Repeating an action ActionScript can repeat an action a specified number of times or while a specific condition exists. Use the while, do...while, for , and for...in actions to create loops. To repeat an action while a condition exists: Use the while statement. A while loop evaluates an expression and executes the code in the body of the loop if the expression is true . After each statement in the body is executed, the expression is evaluated again. In the following example, the loop executes four times: i = 4 while (i > 0) { myMC.duplicateMovieClip("newMC" + i, i ); i --; } You can use the do...while statement to create the same kind of loop as a while loop. In a do...while loop the expression is evaluated at the bottom of the code block so the loop always runs at least once, as in the following: i = 4 do { myMC.duplicateMovieClip("newMC" +i, i ); i --; } while (i > 0); To repeat an action using a built-in counter: Use the for statement. Most loops use a counter of some kind to control how many times the loop runs. You can declare a variable and write a statement that increases or decreases the variable each time the loop executes. In the for action, the counter and the statement that increments the counter are part of the action, as in the following: for (i = 4; i > 0; i--){ myMC.duplicateMovieClip("newMC" + i, i + 10); } To loop through the children of a movie clip or object: Use the for..in statement. Children include other movie clips, functions, objects, and variables. The following example uses trace to print its results in the Output window: myObject = { name:'Joe', age:25, city:'San Francisco' }; for (propertyName in myObject) { trace("myObject has the property: " + propertyName + ", with the value: " + myObject[propertyName]); } This example produces the following results in the Output window: myObject has the property: name, with the value: Joe myObject has the property: age, with the value: 25 myObject has the property: city, with the value: San Francisco You may want your script to iterate over a particular type of child—for example, over only movie clip children. You can do this with for...in in conjunction with the typeof operator. for (name in myMovieClip) { if (typeof (myMovieClip[name]) == "movieclip") { trace("I have a movie clip child named " + name); } } Note: The for..in statement iterates over properties of objects in the iterated object's prototype chain. If a child object's prototype is parent , for..in will also iterate over the properties of parent . See Creating inheritance . For more information on each action, see individual entries in ActionScript dictionary: Overview.
  135.  
  136. <url>html/02_writing_scripts8.html</url>
  137. <title>Using predefined functions</title> Using predefined functions Writing Scripts with ActionScript > Using predefined functions A function is a block of ActionScript code that can be reused anywhere in a movie. If you pass specific values called arguments to a function, the function will operate on those values. A function can also return values. Flash has predefined functions that allow you to access certain information and perform certain tasks, such as collision detection ( hitTest ), getting the value of the last key pressed ( keycode ), and getting the version number of the Flash Player hosting the movie ( getVersion ).   Calling a function You can call a function in any Timeline from any Timeline, including a loaded movie. Each function has its own characteristics and some require you to pass certain values. If you pass more arguments than the function requires, the extra values are ignored. If you don't pass a required argument, the empty arguments are assigned the undefined data type, which can cause errors when you export a script. To call a function, it must be in a frame that the playhead has reached. Flash's predefined functions are listed in the following table: Boolean getTimer isFinite newline scroll escape getVersion isNaN number String eval globalToLocal keycode parseFloat targetPath false hitTest localToGlobal parseInt true getProperty int maxscroll random unescape Note: String functions are deprecated and are not listed in the above table. To call a function in Expert Mode: Use the name of the function. Pass any required arguments inside parentheses. The following example calls the initialize function which requires no arguments: initialize(); To call a function in Normal Mode: Use the evaluate action. Enter the function name and any required arguments in the Expression field. Use the evaluate action to call a function in Normal Mode   To call a function on another Timeline use a target path. For example, to call the function calculateTax that was declared in the instance functionsMovieClip , use the following path: _root.functionsMovieClip.calculateTax(total); Note: Pass any arguments inside the parentheses. For more information on each function, including deprecated string functions, see individual entries in ActionScript dictionary: Overview.
  138.  
  139. <url>html/02_writing_scripts9.html</url>
  140. <title>Creating custom functions</title> Creating custom functions Writing Scripts with ActionScript > Creating custom functions You can define functions to execute a series of statements on passed values. Your functions can also return values. Once a function is defined, it can be called from any Timeline, including the Timeline of a loaded movie. A function can be thought of as a "black box": when a function is called, it is provided with input (arguments). It performs some operation and then generates output (a return value). A well-written function has carefully placed comments about its input, output, and purpose. This way, a user of the function does not need to understand exactly how the function works.   Defining a function Functions, like variables, are attached to the movie clip that defines them. When a function is redefined, the new definition replaces the old definition. To define a function, use the function action followed by the name of the function, any arguments to be passed to the function, and the ActionScript statements that indicate what the function does. The following is a function named Circle with the argument radius: function Circle(radius) { this.radius = radius; this.area = Math.PI * radius * radius; } Note: The keyword this , used in a function body, is a reference to the movie clip that the function belongs to. You can also define a function by creating a function literal . A function literal is an unnamed function that is declared in an expression instead of in a statement. You can use a function literal to define a function, return its value, and assign it to a variable in one expression, as in the following: area = (function () {return Math.PI * radius *radius;})(5);   Passing arguments to a function Arguments are the elements on which a function executes its code. (In this book, the terms argument and parameter are interchangeable.) For example, the following function takes the arguments initials and finalScore : function fillOutScorecard(initials, finalScore) { scorecard.display = initials; scorecard.score = finalScore; } When the function is called, the required arguments must be passed to the function. The function substitutes the passed values for the arguments in the function definition. In this example, scorecard is the instance name of a movie clip; display and score are input text fields in the instance. The following function call assigns the variable display the value "JEB" and the variable score the value 45000 : fillOutScorecard("JEB", 45000); The argument initials in the function fillOutScorecard is similar to a local variable; it exists while the function is called and ceases to exist when the function exits. If you omit arguments during a function call, the omitted arguments are passed as undefined . If you provide extra arguments in a function call that are not required by the function declaration, they are ignored.   Using local variables in a function Local variables are valuable tools for organizing code and making it easier to understand. When a function uses local variables, it can hide its variables from all other scripts in the movie; local variables are scoped to the body of the function and are destroyed when the function exits. Any arguments passed to a function are also treated as local variables. Note: If you modify global variables in a function, use script comments to document these modifications.   Returning values from a function You can use the return action to return values from functions. The return action stops the function and replaces it with the value of the return action. If Flash doesn't encounter a return action before the end of a function, an empty string is returned. For example, the following function returns the square of the argument x : function sqr(x) { return x * x; } Some functions perform a series of tasks without returning a value. For example, the following function initializes a series of global variables: function initialize() { boat_x = _root.boat._x; boat_y = _root.boat._y; car_x = _root.car._x; car_y = _root.car._y; }   Calling a function To invoke a function using the Actions panel in Normal Mode, you use the evaluate action. Pass the required arguments inside parentheses. You can call a function in any Timeline from any Timeline, including a loaded movie. For example, the following statement invokes the function sqr in movie clip MathLib on the main Timeline, passes it the argument 3, and stores the result in the variable temp : var temp = _root.MathLib.sqr(3); In Flash 4, to simulate calling a function you could write a script on a frame after the end of the movie and invoke it by passing the name of the frame label to the call action. For example, if a script that initialized variables was on a frame labeled initialize , you would call it as follows: call("initialize"); This kind of script was not a true function because it could not accept arguments and it could not return a value. Although the call action still functions in Flash 5, its use is not recommended.
  141.  
  142. <url>html/03_interaction1.html</url>
  143. <title>Creating interaction with ActionScript: Overview</title> Creating interaction with ActionScript: Overview Creating Interaction with ActionScript > Creating interaction with ActionScript: Overview An interactive movie involves your audience. Using the keyboard, the mouse, or both, your audience can jump to different parts of movies, move objects, enter information, click buttons, and perform many other interactive operations. You create interactive movies by setting up scripts that run when specific events occur. Events that can trigger a script occur when the playhead reaches a frame, when a movie clip loads or unloads, or when the user clicks a button or presses keys on the keyboard. You use ActionScript to create scripts that tell Flash what action to perform when the event occurs. The following basic actions are common ways to control navigation and user interaction in a movie: Playing and stopping movies Adjusting a movie's display quality Stopping all sounds Jumping to a frame or scene Jumping to a different URL Checking whether a frame is loaded Loading and unloading additional movies For detailed information on these actions, see Flash Help . To create more complex interactivity, you need to understand the following techniques: Creating a custom cursor Getting the mouse position Capturing keypresses Creating a scrolling text field Setting color values Creating sound controls Detecting collisions
  144.  
  145. <url>html/03_interaction2.html</url>
  146. <title>Creating a custom cursor</title> Creating a custom cursor Creating Interaction with ActionScript > Creating a custom cursor To hide the standard cursor (that is, the onscreen representation of the mouse pointer), you use the hide method of the predefined Mouse object. To use a movie clip as the custom cursor, you use the startDrag action. To see an animated demonstration of a custom cursor, drag the mouse in the movie. To create a custom cursor: 1 Create a movie clip to use as a custom cursor. 2 Select the movie clip instance on the Stage. 3 Choose Window > Actions to open the Object Actions panel. 4 In the Toolbox list, select Objects, then select Mouse, and drag hide to the Script window. The code should look like this: onClipEvent(load){ Mouse.hide(); } 5 In the Toolbox list, select Actions; then drag startDrag to the Script window. 6 Select the Lock Mouse to Center box. The code should look like this: onClipEvent(load){ Mouse.hide() startDrag("this", true); } 7 Choose Control > Test Movie to use the custom cursor. Buttons will still function when you use a custom cursor. It's a good idea to put the custom cursor on the top layer of the Timeline so that it moves in front of buttons and other objects as you move the mouse in the movie. For more information about the methods of the Mouse object, see their entries in the ActionScript dictionary: Overview.
  147.  
  148. <url>html/03_interaction3.html</url>
  149. <title>Getting the mouse position</title> Getting the mouse position Creating Interaction with ActionScript > Getting the mouse position You can use the _xmouse and _ymouse properties to find the location of the mouse pointer (cursor) in a movie. Each Timeline has an _xmouse and _ymouse property that returns the location of the mouse within its coordinate system. To see the _xmouse and _ymouse properties within the main Timeline and in a movie clip Timeline, drag the mouse in the movie. The following statement could be placed on any Timeline in the _level0 movie to return the _xmouse position within the main Timeline: x_pos = _root._xmouse; To determine the mouse position within a movie clip, you can use the movie clip's instance name. For example, the following statement could be placed on any Timeline in the _level0 movie to return the _ymouse position in the myMovieClip instance: y_pos = _root.myMovieClip._ymouse You can also determine the mouse position within a movie clip by using the _xmouse and _ymouse properties in a clip action, as in the following: onClipEvent(enterFrame){ xmousePosition = _xmouse; ymousePosition = _ymouse; } The variables x_pos and y_pos are used as containers to hold the values of the mouse positions. You could use these variables in any script in your movie. In the following example, the values of x_pos and y_pos update every time the user moves the mouse. onClipEvent(mouseMove){ x_pos = _root._xmouse; y_pos = _root._ymouse; } For more information about the _xmouse and _ymouse properties, see their entries in the ActionScript Dictionary.
  150.  
  151. <url>html/03_interaction4.html</url>
  152. <title>Capturing keypresses</title> Capturing keypresses Creating Interaction with ActionScript > Capturing keypresses You can use the methods of the predefined Key object to detect the last key the user pressed. The Key object does not require a constructor function; to use its methods, you simply call the object itself, as in the following example: Key.getCode(); You can obtain either virtual key codes or ASCII values of keypresses: To obtain the virtual key code of the last key pressed, use the getCode method. To obtain the ASCII value of the last key pressed, use the getAscii method. A virtual key code is assigned to every physical key on a keyboard. For example, the left arrow key has the virtual key code 37. By using a virtual key code, you can ensure that your movie's controls are the same on every keyboard regardless of language or platform. ASCII (American Standard Code for Information Interchange) values are assigned to the first 127 characters in every character set. ASCII values provide information about a character on the screen. For example, the letter "A" and the letter "a" have different ASCII values. A common place for using Key.getCode is in an onClipEvent handler. By passing keyDown as the parameter, the handler instructs ActionScript to check for the value of the last key pressed only when a key is actually pressed. This movie uses Key.getCode to create navigation controls for the spaceship. You can use the arrow keys to move the spaceship in the movie. To create keyboard controls for a movie: 1 Decide which keys to use and determine their virtual key codes by using one of these approaches: See the list of key codes in Keyboard keys and key code values: Overview . Use a Key object constant. (In the Toolbox list, select Objects, then select Key. Constants are listed in all capital letters.) Assign the following clip action, then choose Control > Test Movie and press the desired key: onClipEvent(keyDown) { trace(Key.getCode()); } 2 Select a movie clip on the Stage. 3 Choose Window > Actions. 4 Double-click the onClipEvent action in the Actions category of the toolbox. 5 Choose the Key down event in the parameters pane. 6 Double-click the if action in the Actions category of the toolbox. 7 Click in the Condition parameter, select Objects; then select Key and getCode . 8 Double-click the equality operator ( == ) in the Operators category of the toolbox. 9 Enter the virtual key code to the right of the equality operator. Your code should look like this: onClipEvent(keyDown) { if (Key.getCode() == 32) { } } 10 Select an action to perform if the correct key is pressed. For example, the following action causes the main Timeline to go to the next frame when the Spacebar (32) is pressed: onClipEvent(keyDown) { if (Key.getCode() == 32) { nextFrame(); } } For more information about the methods of the Key object, see their entries in the ActionScript Dictionary.
  153.  
  154. <url>html/03_interaction5.html</url>
  155. <title>Creating a scrolling text field</title> Creating a scrolling text field Creating Interaction with ActionScript > Creating a scrolling text field You can use the scroll and maxscroll properties to create a scrolling text field. To scroll the text, click the buttons in the movie. In the Text Options panel, you can assign a variable to any text field set to Input Text or Dynamic Text. The text field acts like a window that displays the value of that variable. Each variable associated with a text field has a scroll and a maxscroll property. You can use these properties to scroll text in a text field. The scroll property returns the number of the topmost visible line in a text field; you can set and retrieve it. The maxscroll property returns the topmost visible line in a text field when the bottom line of text is visible; you can read, but not set, this property. For example, suppose you have a text field that is four lines long. If it contains the variable speech , that would fill nine lines of the text field, and only part of the speech variable can be displayed at one time (identified by the solid box): You can access these properties using dot syntax, as in the following: textFieldVariable.scroll myMovieClip.textFieldVariable.scroll textFieldVariable.maxscroll myMovieClip.textFieldVariable.maxscroll To create a scrolling text field: 1 Drag a text field on the Stage. 2 Choose Window > Panels > Text Options. 3 Choose Input Text from the pop-up menu. 4 Enter the variable name text in the Variable field. 5 Drag the text field's bottom right corner to resize the text field. 6 Choose Window > Actions. 7 Select frame 1 in the main Timeline and assign a set variable action that sets the value of text . No text will appear in the field until the variable is set. Therefore, although you can assign this action to any frame, button, or movie clip, it's a good idea to assign the action to frame 1 on the main Timeline, as shown here: 8 Choose Window > Common Libraries > Buttons, and drag a button to the Stage. 9 Press Alt (Windows) or Option (Macintosh) and drag the button to create a copy. 10 Select the top button and choose Window > Actions. 11 Drag the set variables action from the toolbox to the Script window in the Actions panel. 12 Enter text.scroll in the Variable box. 13 Enter text.scroll -1 in the Value box and select the Expression check box. 14 Select the Down Arrow button and assign the following set variables action: text.scroll = text.scroll+1; 15 Choose Control > Test Movie to test the scrolling text field. For more information about the scroll and maxscroll properties, see their entries in the ActionScript Dictionary.
  156.  
  157. <url>html/03_interaction6.html</url>
  158. <title>Setting color values</title> Setting color values Creating Interaction with ActionScript > Setting color values You can use the methods of the predefined Color object to adjust the color of a movie clip. The setRGB method assigns hexadecimal RGB (red, green, blue) values to the object, and the setTransform method sets the percentage and offset values for the red, green, blue, and transparency (alpha) components of a color. The following example uses setRGB to change an object's color based on user input. To change the color of the t-shirt, enter a hex value (for example, cc66ff, or 0033cc) in the text field in the movie. To use the Color object, you need to create an instance of the object and apply it to a movie clip. To set the color value of a movie clip: 1 Select a movie clip on the Stage, and choose Window > Panels > Instance. 2 Enter the instance name colorTarget in the Name box. 3 Drag a text field on the Stage. 4 Choose Window > Panels > Text Options and assign it the variable name input . 5 Drag a button to the Stage and select it. 6 Choose Window > Actions. 7 Drag the set variable action from the toolbox to the Script window. 8 In the Variable box, enter c . 9 In the toolbox, select Objects, then Color, and drag new Color to the Value box. 10 Select the Expression check box. 11 Click the Target Path button and select colorTarget . Click OK. The code in the Script window should look like this: on(release) { c = new Color(colorTarget); } 12 Drag the evaluate action from the toolbox to the Script window. 13 Enter c in the Expression box. 14 In the Objects category of the Toolbox list, select Color; then drag setRGB to the Expression box. 15 Select Functions and drag parseInt to the Expression box. The code should look like this: on(release) { c = new Color(colorTarget); c.setRGB(parseInt(string, radix)); } 16 For the parseInt string argument, enter input . The string to be parsed is the value entered into the editable text field. 17 For the parseInt radix argument, enter 16 . The radix is the base of the number system to be parsed. In this case, 16 is the base of the hexadecimal system that the Color object uses. The code should look like this: on(release) { c = new Color(colorTarget); c.setRGB(parseInt(input, 16)); } 18 Choose Control > Test Movie to change the color of the movie clip. For more information about the methods of the Color object, see their entries in the ActionScript Dictionary.
  159.  
  160. <url>html/03_interaction7.html</url>
  161. <title>Creating sound controls</title> Creating sound controls Creating Interaction with ActionScript > Creating sound controls To control sounds in a movie, you use the predefined Sound object. To use the methods of the Sound object, you must first create a new Sound object. Then you can use the attachSound method to insert a sound from the library into a movie while the movie is running. The Sound object's setVolume method controls the volume and the setPan method adjusts the left and right balance of a sound. To attach a sound to a Timeline: 1 Choose File > Import to import a sound. 2 Select the sound in the library and choose Linkage from the Options menu. 3 Select Export This Symbol and give it the identifier mySound . 4 Select frame 1 in the main Timeline and choose Window > Actions. 5 Drag the set variable action from the toolbox to the Script window. 6 Enter s in the Value box. 7 In the Toolbox list, select Objects, then select Sound, and drag new Sound to the Value box. The code should look like this: s = new Sound(); 8 Double-click the evaluate action in the toolbox. 9 Enter s in the Expression box. 10 In the Objects category of the Toolbox list, select Sound, then drag attachSound to the Expression box. 11 Enter "mySound " in the ID argument of attachSound . 12 Double-click the evaluate action in the toolbox. 13 Enter s in the Expression box. 14 In the Objects category, select Sound, then drag start to the Expression box. The code should look like this: s = new Sound(); s.attachSound("mySound"); s.start(); 15 Choose Control > Test Movie to hear the sound. To create a sliding volume control: 1 Drag a button to the Stage. 2 Select the button and choose Insert > Convert to Symbol. Choose the movie clip behavior. This creates a movie clip with the button on it's first frame. 3 Select the movie clip and choose Edit > Edit Symbol. 4 Select the button and choose Window > Actions. 5 Enter the following actions: on (press) { startDrag ("", false, left, top, right, bottom); dragging = true; } on (release, releaseOutside) { stopDrag (); dragging = false; } The startDrag parameters left , top , right , and bottom are variables set in a clip action. 6 Choose Edit > Edit Movie to return to the main Timeline. 7 Select the movie clip on the Stage. 8 Enter the following actions: onClipEvent (load) { top=_y; left=_x; right=_x; bottom=_y+100; } onClipEvent(enterFrame){ if (dragging==true){ _root.s.setVolume(100-(_y-top)); } } 9 Choose Control > Test Movie to use the volume slider. To create a balance sliding control: 1 Drag a button to the Stage. 2 Select the button and choose Insert > Convert to Symbol. Choose the movie clip property. 3 Select the movie clip and choose Edit > Edit Symbol. 4 Select the button and choose Window > Actions. 5 Enter the following actions: on (press) { startDrag ("", false, left, top, right, bottom); dragging = true; } on (release, releaseOutside) { stopDrag (); dragging = false; } The startDrag parameters left , top , right , and bottom are variables set in a clip action. 6 Choose Edit > Edit Movie to return to the main Timeline. 7 Select the movie clip on the Stage. 8 Enter the following actions: onClipEvent(load){ top=_y; bottom=_y; left=_x-50; right=_x+50; center=_x; } onClipEvent(enterFrame){ if (dragging==true){ _root.s.setPan((_x-center)*2); } } 9 Choose Control > Test Movie to use the balance slider. For more information about the methods of the Sound object, see their entries in the ActionScript Dictionary.
  162.  
  163. <url>html/03_interaction8.html</url>
  164. <title>Detecting collisions</title> Detecting collisions Creating Interaction with ActionScript > Detecting collisions You can use the hitTest method of the MovieClip object to detect collisions in a movie. The hitTest method checks to see if an object has collided with a movie clip and returns a Boolean value ( true or false ). You can use the parameters of the hitTest method to specify the x and y coordinates of a hit area on the Stage, or use the target path of another movie clip as a hit area. Each movie clip in a movie is an instance of the MovieClip object. This allows you to call methods of the object from any instance, as in the following: myMovieClip.hitTest(target); You can use the hitTest method to test the collision of a movie clip and a single point. Move the mouse over the shape in the movie to test the collision. The results of the hitTest are returned in the text field. You can also use the hitTest method to test a collision between two movie clips. To test the collision, drag one movie clip so that it touches the other. The results of the hitTest are returned in the text field. To perform collision detection between a movie clip and a point on the Stage: 1 Select a movie clip on the Stage. 2 Choose Window > Actions to open the Object Actions panel. 3 Double-click trace in the Actions category in the toolbox. 4 Select the Expression check box and enter the following in the Expression box: trace (this.hitTest(_root._xmouse, _root._ymouse, true); This example uses the _xmouse and _ymouse properties as the x and y coordinates for the hit area and sends the results to the Output window in Test-Movie Mode. You can also set a text field on the Stage to display the results or use the results in an if statement. 5 Choose Control > Test Movie and move the mouse over the movie clip to test the collision. To perform collision detection on two movie clips: 1 Drag two movie clips to the Stage and give them the instance names mcHitArea and mcDrag . 2 Create a text field on the Stage and enter status in the Text Options Variable box. 3 Select mcHitArea and choose Window > Actions. 4 Double-click evaluate in the toolbox. 5 Enter the following code in the Expression box by selecting items from the toolbox: _root.status=this.hitTest(_root.mcDrag); 6 Select the onClipEvent action in the Script window and choose enterFrame as the event. 7 Select mcDrag and choose Window > Actions. 8 Double-click startDrag in the toolbox. 9 Select the Lock Mouse to Center check box. 10 Select the onClipEvent action in the Script window and choose the Mouse down event. 11 Double-click stopDrag in the toolbox. 12 Select the onClipEvent action in the Script window and choose the Mouse up event. 13 Choose Control > Test Movie and drag the movie clip to test the collision detection. For more information about the hitTest method, see its entry in the ActionScript Dictionary.
  165.  
  166. <url>html/04_movieclips1.html</url>
  167. <title>Working with movie clips: Overview</title> Working with movie clips: Overview Working with Movie Clips > Working with movie clips: Overview A movie clip is a mini Flash movie: it has its own Timeline and properties. A movie clip symbol in the Library may be used multiple times in a Flash movie; each use is called an instance of the movie clip. Movie clips can be nested inside each other. To distinguish instances from each other, you can assign each instance an instance name. Any object can be placed on the Timeline of a movie clip, including other movie clips. Movies that are loaded into the Flash Player using loadMovie are also mini Flash movies. Each movie clip, loaded movie, and the main Timeline in a Flash movie are objects with properties and methods that can be manipulated by ActionScript to create complex, nonlinear animation and powerful interactivity. You control movie clips using actions and MovieClip object methods. Actions and methods can be attached to frames or buttons in a movie clip (frame and button actions), or to a specific movie clip instance (clip actions). Actions in a movie clip can control any Timeline in a movie. To control a Timeline you must address it by using a target path. A target path indicates the location of the Timeline in the movie. You can also turn a movie clip into a "smart" clip; a movie clip with ActionScript that can be reprogrammed without using the Actions panel. Smart clips make it easy to pass objects with complicated ActionScript logic from a programmer to a designer.
  168.  
  169. <url>html/04_movieclips10.html</url>
  170. <title>Assigning an action or method</title> Using actions and methods to control Timelines Working with Movie Clips > Using actions and methods to control Timelines > Assigning an action or method Actions and methods can be assigned to a button or frame in a Timeline, or to a movie clip instance. To assign an action or method to a movie clip instance you must use an onClipEvent handler. All actions attached to the instance are nested inside an onClipEvent handler and execute after it is triggered. The onClipEvent action is triggered by either Timeline events (such as loading a movie) or user events (such as a mouse click or keypress). For example, onClipEvent(mouseMove) triggers an action every time the user moves the mouse. The onClipEvent action is assigned to an instance on the Stage. The onClipEvent events are listed in the Parameters pane in the Actions panel.  
  171.  
  172. <url>html/04_movieclips11.html</url>
  173. <title>Loading and unloading additional movies</title> Using actions and methods to control Timelines Working with Movie Clips > Using actions and methods to control Timelines > Loading and unloading additional movies You can use the loadMovie action or method to play additional movies without closing the Flash Player, or to switch movies without loading another HTML page. You can also use loadMovie to send variables to a CGI script, which generates a SWF file as its CGI output. When you load a movie, you can specify a level or movie clip target into which the movie will load. The unloadMovie action and method removes a movie previously loaded by loadMovie . Explicitly unloading movies with unloadMovie ensures a smooth transition between movies and can lighten the memory required by the Flash Player. Use the loadMovie action to do any of the following: Play a sequence of banner ads that are SWF files by placing a loadMovie action at the end of each SWF file to load the next movie Develope a branching interface that lets the user choose among several different SWF files Build a navigation interface with navigation controls in level 0 that load other levels. Loading levels produces smoother transitions than loading new HTML pages in a browser.
  174.  
  175. <url>html/04_movieclips12.html</url>
  176. <title>Changing movie clip position and appearance</title> Using actions and methods to control Timelines Working with Movie Clips > Using actions and methods to control Timelines > Changing movie clip position and appearance To change the properties of a movie clip as it plays, you can use the setProperty action or write a statement that assigns a value to a property. If you load a movie into a target, the loaded movie inherits the properties of the targeted movie clip. Once the movie is loaded, you can change those properties. Some properties, called read-only properties, have values that you can read but not set. You can write statements to set any property that is not read-only. The following statement sets the _alpha property of the movie clip instance wheel , which is a child of the car instance: car.wheel._alpha = 50; In addition, you can write statements that get the value of a movie clip property. For example, the following statement gets the value of the _xmouse property on the main Timeline and sets the _x property of the customCursor instance to that value: onClipEvent(enterFrame){ customCursor._x = _root._xmouse; } You can also use the getProperty function to retrieve movie clip properties. The _x , _y , _rotation , _xscale , _yscale , _height , _width , _alpha , and _visible properties are affected by transformations on the movie clip's parent, and transform the movie clip and any of the clip's children. The _focusrect , _highquality , _quality , and _soundbuftime properties are global; they only belong to the level 0 Timeline. All other properties belong to each movie clip or loaded level. The table below lists all the movie clip properties: Properties _alpha _highquality _totalframes _xscale _currentframe _name _url _y _droptarget _quality _visible _ymouse _focusrect _rotation _width _yscale _framesloaded _soundbuftime _x _height _target _xmouse
  177.  
  178. <url>html/04_movieclips13.html</url>
  179. <title>Dragging movie clips</title> Using actions and methods to control Timelines Working with Movie Clips > Using actions and methods to control Timelines > Dragging movie clips You can use the startDrag action or method to make a movie clip draggable while a movie is playing. For example, you can make a draggable movie clip for games, drag-and-drop functions, customizable interfaces, scroll bars, and sliders. A movie clip remains draggable until explicitly stopped by stopDrag , or until another movie clip is targeted with startDrag . Only one movie clip can be dragged at a time. To create more complicated drag-and-drop behavior, you can evaluate the _droptarget property of the movie clip being dragged. For example, you might examine the _droptarget property to see if the movie was dragged to a specific movie clip (such as a "trash can" movie clip), and then trigger another action. See Using "if" statements and Using operators to manipulate values in expressions .
  180.  
  181. <url>html/04_movieclips14.html</url>
  182. <title>Duplicating and removing movie clips</title> Using actions and methods to control Timelines Working with Movie Clips > Using actions and methods to control Timelines > Duplicating and removing movie clips You can create or remove movie clip instances as your movie is playing using duplicateMovieClip or removeMovieClip , respectively. The duplicateMovieClip action and method dynamically create a new instance of the movie clip, assigning it a new instance name and giving it a depth. A duplicated movie clip always starts at frame 1 even if the original movie clip was on another frame when duplicated, and is always on top of all predefined movie clips placed on the Timeline. Variables are not copied into the duplicate movie clip. To delete a movie clip you created with duplicateMovieClip , use removeMovieClip . Duplicated movie clips also are removed if the parent movie clip is deleted.
  183.  
  184. <url>html/04_movieclips15.html</url>
  185. <title>Attaching movie clips</title> Using actions and methods to control Timelines Working with Movie Clips > Using actions and methods to control Timelines > Attaching movie clips You can retrieve a copy of a movie clip from a library and play it as part of your movie using the attachMovie method. This method loads another movie clip into your movie clip and plays it as the movie runs. To use the attachMovie method, the movie clip being attached must be given a unique name in the Symbol Linkage Properties dialog box. To name a movie clip for sharing: 1 Select the movie clip in the movie's Library that you want to attach. 2 In the Library window, choose Linkage from the Options menu. 3 For Linkage, choose Export This Symbol. 4 In the Symbol Linkage Properties dialog box, for Identifier, enter a name for the movie clip. The name must differ from the symbol's name in the library. 5 Click OK. To attach a movie clip to another movie clip: 1 In the Actions panel, specify the target to which you want to attach a movie clip. 2 In the Toolbox list, select the MovieClip object and then select the attachMovie method. 3 Set the following arguments: For idName , specify the Identifier name that you entered in the Symbol Linkage Properties dialog box. For newName , enter an instance name for the attached clip so that you will be able to target it. For depth , enter the level at which the duplicate movie will be attached to the movie clip. Each attached movie has its own stacking order, with level 0 as the level of the originating movie. Attached movie clips are always on top of the original movie clip. For example: myMovieClip.attachMovie("calif", "california", 10 );
  186.  
  187. <url>html/04_movieclips16.html</url>
  188. <title>Creating smart clips</title> Creating smart clips Working with Movie Clips > Creating smart clips A "smart" clip is a movie clip with defined clip parameters that can be changed. Those parameters are then passed to actions in the smart clip that change the clip's behavior. To create a smart clip, you assign clip parameters to a movie clip symbol in the Library. You can write ActionScript statements in the smart clip that operate on the clip parameters, much like you use arguments in a function definition. You can select a smart clip instance on the Stage and change the values of the parameters in the Clip Parameters panel. During playback, the values set in the panel are sent to the smart clip before any actions in the movie are executed. Smart clips are useful for passing complicated Flash elements from a programmer to a designer. The programmer can write actions in the smart clip with variables that control the clip and the movie. A designer can then change the values of those variables in the Clip Parameters panel without having to open the Actions panel. You can use smart clips to create interface elements—such as radio buttons, pop-up menus, tooltips, surveys, games, and avatars. Any movie clip that you want to reuse in a different way without changing the scripts would be a good smart clip. In addition, you can create a custom interface in Flash for the Clip Parameters panel to facilitate designers who are customizing the clip.
  189.  
  190. <url>html/04_movieclips17.html</url>
  191. <title>Defining clip parameters</title> Creating smart clips Working with Movie Clips > Creating smart clips > Defining clip parameters Clip parameters are pieces of data that are passed to a movie clip when it loads in a movie. You can define clip parameters when you are authoring your movie. You can use these parameters in actions to change the appearance and behavior of the smart clip while the movie is playing. A special icon in the Library window indicates a movie clip with defined clip parameters. To define clip parameters for a movie clip: 1 Select a movie clip symbol in your movie's library and do one of the following to display the Clip Parameters dialog box: Right-click (Windows) or Control-click (Macintosh), and choose Define Clip Parameters from the context menu. Choose Define Clip Parameters from the Options menu at the upper right of the Library window. 2 Use the controls in the Clip Parameters dialog box as follows: Click the Add (+) button to add a new name/value pair or additional parameters for a selected name/value pair. Click the Minus (-) button to delete a name/value pair. Use the arrow buttons to change the order of parameters in the list. Select a field by double-clicking it, and then enter a value. 3 For Name, enter a unique identifier for the parameter. 4 For Type, choose the kind of data the parameter will contain from the pop-up menu: Select Default to use a string or number value. Select Array for a dynamic list of items that can grow or shrink. Select Object to declare several related elements with names and values, such as a Point object with x and y elements. Select List to limit the selection to several choices, such as true or false or Red , Green , or Blue . 5 For Value, select the default value that the parameter will contain from the pop-up menu. 6 If you want to use a custom interface for the Clip Parameters panel, do one of the following: Enter a relative path to the custom interface SWF file in the Link to Custom UI field. Click the Link to Custom UI folder, and browse to the custom interface SWF file. See Creating a custom interface . 7 For Description, enter notes to that will appear in the Clip Parameters panel that describe what each parameter does. You can include any information in the Description that you want someone who uses the smart clip to know. For example, an explanation of methods you have defined. 8 Choose Lock in Instance to prevent users from renaming the parameters in the Clip Parameters panel. It is recommended that you leave the parameter names locked. 9 Click OK.
  192.  
  193. <url>html/04_movieclips18.html</url>
  194. <title>Setting clip parameters</title> Creating smart clips Working with Movie Clips > Creating smart clips > Setting clip parameters You can write actions in the smart clip that use the defined parameters to change the behavior of a smart clip. In a simple example, if you define a clip parameter with the name Frame , you could write the following script on the smart clip that uses the Frame parameter: onClipEvent(load){ gotoAndStop(Frame); } You can then select the Smart Clip on the Stage and set the value for the Frame parameter in the Clip Parameters panel to change which frame is played. To set a smart clip's clip parameters: 1 Select a smart clip instance on the Stage. Smart clips are movie clips, so only the first frame will display in authoring mode. 2 Choose Window > Panels > Clip Parameters to display the Clip Parameters panel. 3 In the Clip Parameters panel, do one of the following: Double-click the Value field to select it and enter a value for each parameter. If the parameter has been defined as a List, a pop-up menu will appear. If a custom interface has been defined, use the interface elements provided. 4 Choose Control > Test Movie to see the smart clip's behavior change.
  195.  
  196. <url>html/04_movieclips19.html</url>
  197. <title>Creating a custom interface</title> Creating smart clips Working with Movie Clips > Creating smart clips > Creating a custom interface A custom interface is a Flash movie that lets you enter values to be passed to the smart clip. The custom interface replaces the interface of the Clip Parameters panel. The Clip Parameters panel with a custom interface movie.   The same smart clip without a custom interface in the Clip Parameters panel   Any values you enter using a custom interface are passed from the Clip Parameters panel to the smart clip through an intermediary, or exchange, movie clip in the custom interface. The exchange movie clip must have the instance name xch . If a custom interface is selected in the Define Clip Parameters dialog box, the smart clip instance passes the defined parameters to the xch movie clip and any new values entered in the custom interface are copied to xch and passed back to the smart clip. You must place the xch clip on the main Timeline of the interface movie and xch must always be loaded. The xch movie clip should contain only the values to be passed to the Smart Clip. It should not contain any graphics, other movie clips, or ActionScript statements; xch is merely a container through which values are passed. You can transfer top-level objects, such as Arrays and Objects, through the xch clip. However, you should not pass nested Arrays or Objects. To create a custom interface for a Smart Clip: 1 Choose File > New to create a new Flash movie. 2 Choose Insert > New Symbol to create the exchange movie clip. 3 Create a new layer called "Exchange Clip". 4 With the "Exchange Clip" layer selected, drag the exchange movie clip from the Library window to the Stage in frame 1. 5 Select the exchange movie clip on the Stage, choose Window > Panels > Instance, and enter the name xch . 6 Create the interface elements that the author will interact with to set the clip parameters. For example, a pop-up menu, radio buttons, or drag-and-drop menu items. 7 Use the set variable action to copy variable and object values to the xch instance. For example, if a button is used as an interface element, the button could have an action that sets the value of the variable vertical and passes it to xch , as in the following: on (release){ _root.xch.vertical = true; } 8 Export the movie as a SWF file. To use custom interface SWF with a Smart Clip, you need to link them in the Define Clip Parameters dialog box in the library that contains the Smart Clip. It's a good idea to save the SWF file in the same directory as the FLA containing the Smart Clip. If you reuse the Smart Clip in another file or pass the Smart Clip to another developer, the Smart Clip and the custom interface SWF must remain in the same relative locations.
  198.  
  199. <url>html/04_movieclips2.html</url>
  200. <title>About multiple Timelines</title> About multiple Timelines Working with Movie Clips > About multiple Timelines Every Flash movie has a main Timeline located at level 0 in the Flash Player. You can use the loadMovie action to load other Flash movies (SWF files) into the Flash Player at any level above level 0 (for example, level 1, level 2, level 15). Each movie loaded into a level of the Flash Player has a Timeline. Flash movies at any level can have movie clip instances on their Timelines. Each movie clip instance also has a Timeline and can contain other movie clips that also have Timelines. The Timelines of movie clips and levels in the Flash Player are organized hierarchically so that you can organize and easily control the objects in your movie. The hierarchy of levels and movie clips in the Flash Player   In Flash, this hierarchy of levels and movie clips is called the display list . You can view the display list in the Movie Explorer when you are authoring in Flash. You can view the display list in the Debugger when you are playing the movie in Test-Movie Mode, the stand-alone Flash Player, or in a Web browser. The Movie Explorer shows the hierarchy of Timelines called the "display list"   Timelines in a Flash movie are objects and all have characteristics (properties) and the abilities (methods) of the predefined MovieClip object. Timelines have specific relationships with each other depending on their locations in the display list. Timelines that are nested inside other Timelines are affected by changes made to the Timeline on which they live. For example, if portland is a child of oregon and you change the _xscale property of oregon , portland will also scale. Timelines can also send messages to each other. For example, an action on the last frame of one movie clip could tell another movie clip to play.
  201.  
  202. <url>html/04_movieclips3.html</url>
  203. <title>About the hierarchical relationship of Timelines</title> About multiple Timelines Working with Movie Clips > About multiple Timelines > About the hierarchical relationship of Timelines When you place a movie clip instance on another movie clip's Timeline, one movie clip symbol contains the instance of the other movie clip—the first movie clip is the child and the second movie clip is its parent . The main Timeline of a Flash movie is the parent of all the movie clips on its level. The parent-child relationships of movie clips are hierarchical. To understand this hierarchy, consider the hierarchy on a computer: the hard drive has a root directory (or folder) and subdirectories. The root directory is analogous to the main Timeline of a Flash movie: it is the parent of everything else. The subdirectories are analogous to movie clips. You can use subdirectories to organize related content. Similarly, you can use the movie clip hierarchy in Flash to organize related visual objects, often in ways similar to the real-world behavior of objects. Any change you make to a parent movie clip is also performed on its children. For example, you could create a Flash movie that has a car that moves across the Stage. You could use a movie clip symbol to represent the car and set up a motion tween to move it across the Stage. A motion tween moves the car movie clip on the main Timeline   The car is viewed from the side, with two wheels visible. Once you have the car moving, you want to add wheels that rotate. So you make a movie clip for a car wheel, and create two instances of this movie clip, named frontWheel and backWheel . Then you place the wheels on the Timeline of the car movie clip —not on the main Timeline. As children of car , frontWheel and backWheel are affected by any changes made to car . This means that they will move with the car as it tweens across the Stage. The frontWheel and backWheel instances are placed on the Timeline of the car movie clip.   To make the wheels rotate, you can set up a motion tween to rotate the wheel symbol to make both instances spin. Even after you change frontWheel and backWheel , they will continue to be affected by the tween on their parent movie clip, car ; the wheels will spin, but they will also move with the parent movie clip car across the Stage. The wheel symbol in Edit Symbol Mode  
  204.  
  205. <url>html/04_movieclips4.html</url>
  206. <title>Sending messages between Timelines</title> About multiple Timelines Working with Movie Clips > About multiple Timelines > Sending messages between Timelines You can send messages from one Timeline to another. One Timeline contains the action, called the controller , and another receives the action, called the target . You can assign an action to a frame or button in a Timeline, or, if the Timeline is a movie clip, to the movie clip itself. To target Timelines, you can use actions from the Actions category, or you can use methods of the MovieClip object from the Objects category in the Actions panel. For example, you can use the duplicateMovieClip action to target and make copies of movie clip instances while a movie plays. You can use actions from the Actions category to target a Timeline.   You can use methods of the MovieClip object to target a Timeline.   To perform multiple actions on the same target, you can use the with action. Similar to the JavaScript with statement, the ActionScript with action is a wrapper that lets you address the targeted Timeline once, and then have a series of actions execute on that clip; you don't have to address the targeted Timeline in each action. You can also use the tellTarget action to perform multiple actions on the same target. To communicate between Timelines, you must do the following: Enter an instance name for the target movie clip. To name a movie clip instance, use the Instance Panel (Window > Panels > Instance). Timelines loaded into levels use their level number as an instance name, for example, _level6 . Enter the target path to the instance name in the Actions Panel. You can enter the target path manually, or you can use the Insert Target Path dialog box to target a movie clip. See Specifying target paths . Note: During playback, a movie clip's Timeline must be on the Stage to be targeted.
  207.  
  208. <url>html/04_movieclips5.html</url>
  209. <title>About absolute and relative target paths</title> About multiple Timelines Working with Movie Clips > About multiple Timelines > About absolute and relative target paths A target path is the address of the Timeline you want to target. The display list of Timelines in Flash is similar to the hierarchy of files and folders on a Web server. The Movie Explorer shows the display list of movie clips in Authoring Mode.   Just as on a Web server, each Timeline in Flash can be addressed two ways: with an absolute path or a relative path. The absolute path of an instance is always the same, regardless of which Timeline calls the action; for example, the absolute path to the instance california is always _level0.westCoast.california . A relative path is different when called from different locations; for example, the relative path to california from sanfrancisco is _parent , but from portland , it's _parent._parent.california . Note: For more information about the Movie Explorer, see Flash Help. An absolute path starts with the name of the level into which the movie is loaded and continues through the display list until it reaches the target instance. The first movie to be opened in the Flash Player is loaded at level 0. You must assign each additional loaded movie a level number. The target name for a level is _levelX where X is the level number into which the movie is loaded. For example, the first movie opened in the Flash Player is called _level0 , a movie loaded into level 3 is called _level3 . In the following example, two movies have been loaded into the player, TargetPaths.swf at level 0, and EastCoast.swf at level 5. The levels are indicated in the Debugger, with level 0 indicated as _root . The Debugger shows the absolute paths of all Timelines in the display list in Test-Movie Mode.   An instance always has the same absolute path, whether it's being called from an action in an instance on the same level, or from an action on a different level. For example, the instance bakersfield on level 0 always has the following absolute path in dot syntax: _level0.california.bakersfield In slash syntax, the absolute path substitutes slashes for dots, as in the following: _level0/california/bakersfield To communicate between movies on different levels, you must use the level name in the target path. For example, the portland instance would address the atlanta instance as follows: _level5.georgia.atlanta In dot syntax, you can use the alias _root to refer to the main Timeline of the current level. For the main Timeline, or _level0 , the _root alias stands for _level0 when targeted by a clip also on _level0 . For a movie loaded into _level5 , _root is equal to _level5 when targeted by a movie clip also on level 1. For example, an action called from the instance southcarolina could use the following absolute path to target the instance florida : _root.eastCoast.florida In slash syntax, you can use / to refer to the main Timeline of the current level, as in the following: /eastCoast/florida In dot syntax in either Absolute or Relative Mode, you can use the same target path rules to identify a variable on a Timeline or a property of an object. For example, the following statement sets the variable name in the instance form to the value "Gilbert" : _root.form.name = "Gilbert"; In slash syntax in either Absolute or Relative Mode, you can identify a variable on a Timeline by preceding the variable name with a colon ( : ), as in the following: /form:name = "Gilbert"; A relative path is dependent on the relationship between the controller Timeline and the target Timeline. You can use a relative path to reuse actions because the same action can target different Timelines depending on where the action is placed. Relative paths can address targets only within their own level of the Flash Player; they cannot address movies loaded into other levels. For example, you can't use a relative path in an action on _level0 that targets a Timeline on _level5 . In dot syntax, you can use the keyword this in a relative target path to refer to the current Timeline. You can use the alias _parent in a relative target path to indicate the parent Timeline of the current Timeline. The _parent alias can be used repeatedly to go up one level in the movie clip hierarchy within the same level of the Flash Player. For example, _parent._parent controls a movie clip up two levels in the hierarchy. In the following example, each city ( charleston , atlanta , and staugustine ) is a child of a state instance and each state ( southcarolina , georgia , and florida ) is a child of the eastCoast instance. The Movie Explorer shows the parent-child relationships of movie clips.   An action on the Timeline of the instance charleston could use the following target path to target the instance southcarolina : _parent To target the instance eastCoast from an action in charleston , you could use the following relative path: _parent._parent In slash syntax, you can use two dots ( .. ) to go up a level in the hierarchy. To target eastCoast from an action in charleston , you could use the following path: ../.. To target the instance atlanta from an action on the Timeline of charleston , you could use the following relative path in dot syntax: _parent._parent.georgia.atlanta Relative paths are useful for reusing scripts. For example, you could attach a script to a movie clip that magnifies the movie clip up one level by 150%, as follows: onClipEvent (load) { _ parent._xscale = 150; _parent._yscale = 150; } You could then reuse this script by placing it on the Timeline of any movie clip. For more information on addressing and dot syntax, see Chapter 2, "Writing Scripts with ActionScript". For more information on Dot syntax and Slash syntax, see Using ActionScript's syntax .
  210.  
  211. <url>html/04_movieclips6.html</url>
  212. <title>Specifying target paths</title> About multiple Timelines Working with Movie Clips > About multiple Timelines > Specifying target paths To control a movie clip or loaded movie, you must use a target path to specify a target. A movie clip must have an instance name to be targeted. You can specify a target in several different ways: Enter a target path using the Insert Target Path button and dialog box in the Actions panel. Enter the target path of the movie clip in your script manually. Create an expression by using a reference to a movie clip, or by using the predefined functions targetPath and eval . To insert a target path using the Insert Target Path dialog box: 1 Select the movie clip, frame, or button instance to which you want to assign the action. This will be the controller Timeline. 2 Choose Window > Actions to display the Actions panel. 3 In the Toolbox list, choose an action from the Actions category or a method from the MovieClip category inside the Objects category. 4 Click the Target field or location in the script to insert the target path. 5 Click the Insert Target Path button in the bottom right corner of the Actions panel to display the Insert Target Path dialog box. 6 In the Insert Target Path dialog box, choose a syntax: Dots (the default) or Slashes. 7 Choose Absolute or Relative for the target path mode. See About absolute and relative target paths . 8 Specify your target by doing one of the following: Select a movie clip in the Insert Target Path display list. Enter a target manually in the Target field using an absolute or relative path and dot syntax. 9 Click OK. To insert a target path manually: Follow steps 1-4 above and enter an absolute or relative target path into the Actions panel. To use an expression as a target path: 1 Follow steps 1-4 above. 2 Do one of the following: Manually enter a reference as a target path. A reference is evaluated to determine the target path. You can use a reference as a parameter for the with action. In the following example, the variable index is evaluated and multiplied by 2. The resulting value is used as the name of the movie clip inside the Block instance that is told to play: with (Board.Block[index*2]) { play(); } In the Functions category of the Toolbox list, choose the targetPath function. The targetPath function converts a reference to a movie clip into a string that can be used by actions such as tellTarget . In the following example, the targetPath function converts the reference Board.Block[index*2+1] to a string: tellTarget (targetPath (Board.Block[index*2+1])) { play(); } The previous example is equivalent to the following Slash syntax: tellTarget ("Board/Block:" + index*2+1)) { play(); } In the Functions category of the Toolbox list, choose the eval function. The eval function converts a string into a reference to a movie clip that can be used as a target path by actions such as with . The following script evaluates the variable i , adds it to the string "cat" and assigns the resulting value to the variable x . The variable x is now a reference to a movie clip instance and can call the MovieClip object methods, as in the following: x = eval ("cat" + i); x.play(); You can also use the eval function to call methods directly, as in the following: eval ("cat" + i).play();.
  213.  
  214. <url>html/04_movieclips7.html</url>
  215. <title>Using actions and methods to control Timelines</title> Using actions and methods to control Timelines Working with Movie Clips > Using actions and methods to control Timelines You can use certain actions and methods of the MovieClip object to target , or perform tasks on, a movie clip or loaded level. For example, the setProperty action sets a property (such as _width ) of a Timeline to a value (such as 100 ). Some MovieClip object methods duplicate the function of all the actions that target Timelines. There are also additional methods, such as hitTest , and swapDepths . Whether you use an action or a method, the target Timeline must be loaded in the Flash Player when the action or method is called. The following actions can target movie clips: loadMovie , unloadMovie , setProperty , startDrag , duplicateMovieClip , and removeMovieClip . To use these actions, you must enter a target path in the action's Target parameter to indicate the recipient of the action. Some of these actions can target movie clips or levels and others can only target movie clips. The following MovieClip object methods can control movie clips or loaded levels and do not have equivalent actions: attachMovie , getBounds , getBytesLoaded , getBytesTotal , globalToLocal , localToGlobal , hitTest , and swapDepths . When an action and a method offer similar functions, you can choose to control movie clips by using either one. The choice depends on your preference and familiarity with writing scripts in ActionScript. For more information about the methods of the MovieClip object and for information about each action, see Chapter 7, "ActionScript Dictionary"
  216.  
  217. <url>html/04_movieclips8.html</url>
  218. <title>About methods versus actions</title> Using actions and methods to control Timelines Working with Movie Clips > Using actions and methods to control Timelines > About methods versus actions To use a methods, you invoke it by using the target path to the instance name, followed by a dot, and then the method name and arguments, as in the following statements: myMovieClip.play(); parentClip.childClip.gotoAndPlay(3); In the first statement, the play method causes the myMovieClip instance to play. In the second statement, the gotoAndPlay method sends the playhead in childClip (which is a child of the instance parentClip ) to frame 3 and plays. Actions that control a Timeline have a Target parameter that specifies the target path. For example, in the following script the startDrag action targets the customCursor instance and makes it draggable: on(press){ startDrag("customCursor"); } When you use a method, you call the method at the end of the target path. For example, the following statement performs the same startDrag function: customCursor.startDrag(); Statements written using the MovieClip object methods tend to be more brief because they don't require the tellTarget action. Use of the tellTarget action is discouraged because it is not compatible with the ECMA-262 standard. For example, to tell movie clip myMovieClip to start playing using the MovieClip object methods, you would use the following code: myMovieClip.play(); The following code produces the same results by using the tellTarget action: tellTarget ("myMovieClip") { play(); }
  219.  
  220. <url>html/04_movieclips9.html</url>
  221. <title>Using multiple methods or actions to target a Timeline</title> Using actions and methods to control Timelines Working with Movie Clips > Using actions and methods to control Timelines > Using multiple methods or actions to target a Timeline You can use the with action to address a targeted movie clip once, and then execute a series of actions on that clip. The with action works on all ActionScript objects (for example Array, Color, and Sound), not just movie clips. The tellTarget action is similar to the with action. However, the tellTarget action is not preferred because it does not work with all ActionScript objects and is not ECMA-262 compliant. The with action takes an object as a parameter. The object that you specify is added to the end of the current target path. All actions nested inside a with action are carried out inside the new target path, or scope . For example, in the following script on the main Timeline, the with action is passed the object donut.hole to change the properties of hole : with (donut.hole){ _alpha = 20; _xscale = 150; _yscale = 150; } It is as if the statements inside the with action were called from the Timeline of the hole instance. In the following example, note the economy of using the with action and the methods of the MovieClip object to issue several instructions: with (myMovieClip) { _x -= 10; _y += 10; gotoAndPlay(3); } For more information on the tellTarget action, see Flash Help .
  222.  
  223. <url>html/05_integrating1.html</url>
  224. <title>Integrating Flash with Web Applications: Overview</title> Integrating Flash with Web Applications: Overview Integrating Flash with Web Applications > Integrating Flash with Web Applications: Overview Flash movies can send information to and load information from remote files. To send and load variables, you use the loadVariables or getURL action. To load a Flash Player movie from a remote location, you use the loadMovie action. To send and load XML data, you use the XML or XMLSocket object. You can structure XML data using the predefined XML object methods. You can also create Flash forms consisting of common interface elements, such as text fields and pop-up menus, to collect data that will be sent to a server-side application. To extend Flash so that it can send and receive messages from the movie's host environment—for example, the Flash Player or a JavaScript function in a Web browser—you can use fscommand and Flash Player methods.
  225.  
  226. <url>html/05_integrating10.html</url>
  227. <title>Verifying entered data</title> Creating forms Integrating Flash with Web Applications > Creating forms > Verifying entered data For a form that passes variables to an application on a Web server, you'll want to verify that users are entering proper information. For example, you don't want users to enter text in a phone number field. Use a series of set variable actions in conjunction with for and if to evaluate entered data. The following sample action checks to see whether the entered data is a number, and that the number is in the format ###-###-####. If the data is valid, the message "Good, this is a valid phone number!" is displayed. If the data is not valid, the message "This phone number is invalid!" is displayed. To use this script in a movie, create two text fields on the Stage and choose Input in the Text Options panel for each. Assign the variable phoneNumber to one text field and assign the variable message to the other. Attach the following action to a button on the Stage next to the text fields: on (release) { valid = validPhoneNumber(phoneNumber); if (valid) { message = "Good, this is a valid phone number!"; } else { message = "This phone number is invalid!"; } function isdigit(ch) { return ch.length == 1 && ch >= '0' && ch <= '9'; } function validPhoneNumber(phoneNumber) { if (phoneNumber.length != 12) { return false; } for (var index = 0; index < 12; index++) { var ch = phoneNumber.charAt(index); if (index == 3 || index == 7) { if (ch != "-") { return false; } } else if (!isdigit(ch)) { return false; } } return true; } } To send the data, create a button that has an action similar to the following: (Replace the getURL arguments with arguments appropriate for your movie.) on (release) { if (valid) { getURL("http://www.webserver.com", "_self", "GET"); } } For more information about these ActionScript statements, see set , for , and if in Chapter 7, "ActionScript Dictionary."
  228.  
  229. <url>html/05_integrating11.html</url>
  230. <title>Sending messages to and from the Flash Player</title> Sending messages to and from the Flash Player Integrating Flash with Web Applications > Sending messages to and from the Flash Player To send messages from a Flash movie to its host environment (for example, a Web browser, a Director movie, or the stand-alone Flash Player), you can use the fscommand action. This allows you to extend your movie by using the capabilities of the host. For example, you could pass an fscommand action to a JavaScript function in an HTML page that opens a new browser window with specific properties. To control a movie in the Flash Player from Web browser scripting languages such as JavaScript, VBScript, and Microsoft JScript, you can use Flash Player methods—functions that send messages from a host environment to the Flash movie. For example, you could have a link in an HTML page that sends your Flash movie to a specific frame.
  231.  
  232. <url>html/05_integrating12.html</url>
  233. <title>Using fscommand</title> Sending messages to and from the Flash Player Integrating Flash with Web Applications > Sending messages to and from the Flash Player > Using fscommand Use the fscommand action to send a message to whichever program is hosting the Flash Player. The fscommand action has two parameters: command and arguments . To send a message to the stand-alone version of the Flash Player, you must use predefined commands and arguments. For example, the following action sets the stand-alone player to scale the movie to the full monitor screen size when the button is released: on(release){ fscommand("fullscreen", "true"); } The following table shows the values you can specify for the command and arguments parameters of the fscommand action to control a movie playing in the stand-alone player (including projectors): Command Arguments Purpose quit None Closes the projector. fullscreen true or false Specifying true sets the Flash Player to full-screen mode. Specifying false returns the player to normal menu view. allowscale true or false Specifying false sets the player so that the movie is always drawn at its original size and never scaled. Specifying true forces the movie to scale to 100% of the player. showmenu true or false Specifying true enables the full set of context menu items. Specifying false dims all the context menu items except About Flash Player. exec Path to application Executes an application from within the projector. To use fscommand to send a message to a scripting language such as JavaScript in a Web browser, you can pass any two arguments in the command and arguments parameters. These arguments can be strings or expressions and will be used in a JavaScript function that "catches," or handles, the fscommand action. An fscommand action invokes the JavaScript function moviename _DoFSCommand in the HTML page that embeds the Flash movie, where moviename is the name of the Flash Player as assigned by the NAME attribute of the EMBED tag or the ID attribute of the OBJECT tag. If the Flash Player is assigned the name myMovie , the JavaScript function invoked is myMovie_DoFSCommand . To use the fscommand action to open a message box from a Flash movie in the HTML page through JavaScript: 1 In the HTML page that embeds the Flash movie, add the following JavaScript code: function theMovie_DoFSCommand(command, args) { if (command == "messagebox") { alert(args); } } If you publish your movie using the Flash with FSCommand template in the HTML Publish Settings, this code is inserted automatically. The movie's NAME and ID attributes will be the file name. For example, for the file myMovie.fla , the attributes would be set to myMovie . For more information about publishing, see Flash Help. 2 In the Flash movie, add the fscommand action to a button: fscommand("messagebox", "This is a message box invoked from within Flash.") You can also use expressions for the fscommand action and arguments, as in the following example: fscommand("messagebox", "Hello, " & name & ", welcome to our Web site!") 3 Choose File > Publish Preview > HTML to test the movie. The fscommand action can send messages to Macromedia Director that are interpreted by Lingo as strings, events, or executable Lingo code. If the message is a string or an event, you must write the Lingo code to receive it from the fscommand action and carry out an action in Director. For more information, see the Director Support Center . In Visual Basic, Visual C++, and other programs that can host ActiveX controls, fscommand sends a VB event with two strings that can be handled in the environment's programming language. For more information, use the keywords Flash method to search the Flash Support Center .
  234.  
  235. <url>html/05_integrating13.html</url>
  236. <title>About Flash Player methods</title> Sending messages to and from the Flash Player Integrating Flash with Web Applications > Sending messages to and from the Flash Player > About Flash Player methods You can use Flash Player methods to control a movie in the Flash Player from Web browser scripting languages such as JavaScript and VBScript. As with other methods, you can use Flash Player methods to send calls to Flash Player movies from a scripting environment other than ActionScript. Each method has a name, and most methods take arguments. An argument specifies a value that the method operates upon. The calculation performed by some methods returns a value that can be used by the scripting environment. There are two different technologies that enable communication between the browser and the Flash Player: LiveConnect (Netscape Navigator 3.0 or later on Windows 95/98/2000/NT or Power Macintosh) and ActiveX (Microsoft Internet Explorer 3.0 and later on Windows 95/98/2000/NT). Although the techniques for scripting are similar for all browsers and languages, there are additional properties and events available for use with ActiveX controls. For more information, including a complete list of the Flash Player scripting methods, use the keywords Flash method to search the Flash Support Center .
  237.  
  238. <url>html/05_integrating2.html</url>
  239. <title>Sending and loading variables to and from a remote file</title> Sending and loading variables to and from a remote file Integrating Flash with Web Applications > Sending and loading variables to and from a remote file A Flash movie is a window for capturing and displaying information, much like an HTML page. Flash movies, unlike HTML pages, can stay loaded in the browser and continuously update with new information without having to refresh. You can use Flash actions and object methods to send information to and receive information from server-side scripts, text files, and XML files. Server-side scripts can request specific information from a database and relay it back and forth between the database and a Flash movie. Server-side scripts can be written in many different languages: some of the most common are Perl, ASP (Microsoft Active Server Pages), and PHP. Storing information in a database and retrieving it allows you to create dynamic and personalized content for your movie. For example, you could create a message board, personal profiles for users, or a shopping cart that remembers what a user has purchased so that it can determine the user's preferences. You can use several ActionScript actions and object methods to pass information into and out of a movie. Each action and method uses a protocol to transfer information. Each also requires information to be formatted in a certain way. The following actions use HTTP or HTTPS protocol to send information in URL encoded format: getURL , loadVariables , loadMovie . The following methods use HTTP or HTTPS protocol to send information as XML: XML.send , XML.load , XML.sendAndLoad . The following methods create and use a TCP/IP socket connection to send information as XML: XMLSocket.connect , XMLSocket.send .   About security When playing a Flash movie in a Web browser, you can load data into the movie only from a file that is on a server in the same subdomain. This prevents Flash movies from being able to download information from other people's servers. To determine the subdomain of a URL consisting of one or two components, use the entire domain: Domain Subdomain http://macromedia macromedia http://macromedia.com macromedia.com To determine the subdomain of a URL consisting of more than two components, remove the last level: Domain Subdomain http://x.y.macromedia.com y.macromedia.com http://www.macromedia.com macromedia.com The following chart shows how the Flash Player determines whether or not to permit an HTTP request: When you use the XMLSocket object to create a socket connection with a server, you must use a port numbered 1024 or higher. (Ports with lower numbers are commonly used for Telnet, FTP, the World Wide Web, or Finger.) Flash relies on standard browser and HTTP and HTTPS security features. Essentially, Flash offers the same security that is available with standard HTML. You should follow the same rules that you follow when building secure HTML Web sites. For example, to support secure passwords in Flash, you need to establish your password authentication with a request to a Web server. To create a password, use a text field to request a password from the user. Submit it to a sever in a loadVariables action or in an XML.sendAndLoad method using an HTTPS URL with the POST method. The Web server can then verify whether the password is valid. This way, the password will never be available in the SWF file.   Checking for loaded data Each action and method that loads data into a movie (except XMLSocket.send ) is asynchronous ; the results of the action are returned at an indeterminate time. Before you can use loaded data in a movie, you must check to see if it has been loaded. For example, you can't load variables and manipulate the values of those variables in the same script. In the following script, you can't use the variable lastFrameVisited until you're sure the variable has loaded from the file myData.txt : loadVariables("myData.txt", 0); gotoAndPlay(lastFrameVisited); Each action and method has a specific technique you can use to check data it has loaded. If you use the loadVariables or loadMovie actions you can load information into a movie clip target and use the data event of the onClipEvent action to execute a script. If you use the loadVariables action to load the data, the onClipEvent(data) action executes when the last variable is loaded. If you use the loadMovie action to load the data, the onClipEvent(data) action executes each time a fragment of the movie is streamed into the Flash Player. For example, the following button action loads the variables from the file myData.txt into the movie clip loadTargetMC : on(release){ loadVariables("myData.txt", _root.loadTargetMC); } An action assigned to the loadTargetMC instance uses the variable lastFrameVisited , which is loaded from the file myData.txt . The following action will execute only after all the variables, including lastFrameVisited , are loaded: onClipEvent(data) { goToAndPlay(lastFrameVisited); } If you use the XML.load and XMLSocket.connect methods, you can define a handler that will process the data when it arrives. A handler is a property of the XML or XMLSocket object to which you assign a function that you have defined. The handlers are called automatically when the information is received. For the XML object, use XML.onLoad . For the XMLSocket object, use XMLSocket.onConnect . For more information, see Using the XML object and Using the XMLSocket object .
  240.  
  241. <url>html/05_integrating3.html</url>
  242. <title>Using loadVariables, getURL, and loadMovie</title> Sending and loading variables to and from a remote file Integrating Flash with Web Applications > Sending and loading variables to and from a remote file > Using loadVariables, getURL, and loadMovie The loadVariables , getURL , and loadMovie actions all communicate with server-side scripts using the HTTP protocol. Each action sends all the variables from the Timeline to which the action is attached; each action handles its response as follows: getURL returns any information to a browser window, not into the Flash Player. loadVariables loads variables into a specified Timeline in the Flash Player. loadMovie loads a movie into a specified level in the Flash Player. When you use the loadVariables , getURL , or loadMovie actions, you can specify several arguments: URL is the file in which the remote variables reside. Location is the level or target in the movie that receives the variables. For more information about levels and targets, see About multiple Timelines . Note: The getURL action does not take this argument. Variables sets the HTTP method, either GET or POST , by which the variables will be sent. For example, if you wanted to track the high scores for a game, you could store the scores on a server and use a loadVariables action to load them into the movie each time someone played the game. The action might look something like this: loadVariables("http://www.mySite.com/scripts/high_score.php", _root.scoreClip, GET); This loads variables from the PHP script called high_score.php into the movie clip instance scoreClip using the GET HTTP method. Any variables loaded with the loadVariables action must be in the standard MIME format application/x-www-urlformencoded (a standard format used by CGI scripts). The file that you specify in the URL argument of the loadVariables action must write out the variable and value pairs in this format so that Flash can read them. The file can specify any number of variables; variable and value pairs must be separated with an ampersand ( & ) and words within a value must be separated with a plus ( + ). For example, this phrase defines several variables: highScore1=54000&playerName1=rockin+good&highScore2=53455&playerName2=bonehelmet&highScore3=42885&playerName3=soda+pop For more information on loadVariables , getURL , and loadMovie , see their entries in the ActionScript Dictionary.
  243.  
  244. <url>html/05_integrating4.html</url>
  245. <title>About XML</title> Sending and loading variables to and from a remote file Integrating Flash with Web Applications > Sending and loading variables to and from a remote file > About XML XML ( Extensible Markup Language ) is becoming the standard for the interchange of structured data in Internet applications. You can integrate data in Flash with servers that use XML technology to build sophisticated applications, such as a chat system or a brokerage system. In XML, as with HTML, you can use tags to markup , or specify, a body of text. In HTML, you can use predefined tags to indicate how text should appear in a Web browser (for example, the <b> tag indicates that text should be bold). In XML, you define tags that identify the type of a piece of data (for example, <password>VerySecret</password> ). XML separates the structure of the information from the way it's displayed. This allows the same XML document to be used and reused in different environments. Every XML tag is called a node , or an element. Each node has a type (1-XML element, or 3-text node) and elements may also have attributes. A node nested in a node is called a child or a childNode . This hierarchical tree structure of nodes is called the XML DOM (Document Object Model)—much like the JavaScript DOM, which is the structure of elements in a Web browser. In the following example, <PORTFOLIO> is the parent node; it has no attributes and contains the childNode <HOLDING> , which has the attributes SYMBOL , QTY , PRICE , and VALUE : <PORTFOLIO> <HOLDING SYMBOL="RICH" QTY="75" PRICE="245.50" VALUE="18412.50" /> </PORTFOLIO>
  246.  
  247. <url>html/05_integrating5.html</url>
  248. <title>Using the XML object</title> Sending and loading variables to and from a remote file Integrating Flash with Web Applications > Sending and loading variables to and from a remote file > Using the XML object You can use the methods of the ActionScript XML object (for example, appendChild , removeNode , and insertBefore ) to structure XML data in Flash to send to a server and to manipulate and interpret downloaded XML data. You can use the following XML object methods to send and load XML data to a server via the HTTP POST method: load downloads XML from a URL and places it in an ActionScript XML object. send passes an XML object to a URL. Any returned information is sent to another browser window. sendAndLoad sends an XML object to a URL. Any returned information is placed in an ActionScript XML object. For example, you could create a brokerage system for trading securities that stores all its information (user names, passwords, session IDs, portfolio holdings, and transaction information) in a database. The server-side script that passes information between Flash and the database reads and writes the data in XML format. You can use ActionScript to convert information collected in the Flash movie (for example, a username and password) to an XML object and then send the data to the server-side script as an XML document. You can also use ActionScript to load the XML document that the server returns into an XML object to be used in the movie. The flow and conversion of data between a Flash Player movie, a server-side scripting document, and a database   The password validation for the brokerage system requires two scripts: a function defined on frame 1, and a script that creates and sends the XML objects attached to the Submit button in the form. When users enter their information into text fields in the Flash movie with the variables username and password , the variables must be converted to XML before being passed to the server. The first section of the script loads the variables into a newly created XML object called loginXML . When a user presses the Submit button, the loginXML object is converted to a string of XML and sent to the server. The following script is attached to the Submit button. To understand the script, read the commented lines of each script as indicated by the characters // : on (release) { // A. Construct a XML document with a LOGIN element loginXML = new XML(); loginElement = loginXML.createElement("LOGIN"); loginElement.attributes.username = username; loginElement.attributes.password = password; loginXML.appendChild(loginElement); // B. Construct a XML object to hold the server's reply loginReplyXML = new XML(); loginReplyXML.onLoad = onLoginReply; // C. Send the LOGIN element to the server, // place the reply in loginReplyXML loginXML.sendAndLoad("https://www.imexstocks.com/main.cgi", loginReplyXML); } The first section of the script generates the following XML when the user presses the SUBMIT button: <LOGIN USERNAME="JeanSmith" PASSWORD="VerySecret" /> The server receives the XML, generates an XML response, and sends it back to the Flash movie. If the password is accepted, the server responds with the following: <LOGINREPLY STATUS="OK" SESSION="rnr6f7vkj2oe14m7jkkycilb" /> This XML includes a SESSION attribute which contains a unique, randomly generated session ID, which will be used in all communications between the client and server for the rest of the session. If the password is rejected, the server responds with the following message: <LOGINREPLY STATUS="FAILED" /> The LOGINREPLY XML node must load into a blank XML object in the Flash movie. The following statement creates the XML object loginreplyXML to receive the XML node: // B. Construct an XML object to hold the server's reply loginReplyXML = new XML(); loginReplyXML.onLoad = onLoginReply; The second statement assigns the onLoginReply function to the loginReplyXML.onLoad handler. The LOGINREPLY XML element arrives asynchronously, much like the data from a loadVariables action, and loads into the loginReplyXML object. When the data arrives, the onLoad method of the loginReplyXML object is called. You must define the onLoginReply function and assign it to the loginReplyXML.onLoad handler so that it can process the LOGINREPLY element. The onLoginReply function is assigned to the frame that contains the submit button. The onLoginReply function is defined on the first frame of the movie.   The onLoginReply function is defined in the first frame of the movie. To understand the script, read the commented lines of each script as indicated by the characters // : function onLoginReply() { // Get the first XML element var e = this.firstChild; // If the first XML element is a LOGINREPLY element with // status OK, go to the portfolio screen. Otherwise, // go to the login failure screen and let the user try again. if (e.nodeName == "LOGINREPLY" && e.attributes.status == "OK") { // Save the session ID for future communications with server sessionID = e.attributes.session; // Go to the portfolio viewing screen gotoAndStop("portfolioView"); } else { // Login failed! Go to the login failure screen. gotoAndStop("loginFailed"); } } The first line of this function, var e = this.firstChild , uses the keyword this to refer to the XML object loginReplyXML that has just been loaded with XML from the server. You can use this because onLoginReply has been invoked as loginReplyXML.onLoad , so even though onLoginReply appears to be a plain function, it actually behaves as a method of loginReplyXML . To send the username and password as XML to the server and to load an XML response back into the Flash movie, you can use the sendAndLoad method, as in the following: // C. Send the LOGIN element to the server, // place the reply in loginReplyXML loginXML.sendAndLoad("https://www.imexstocks.com/main.cgi", loginReplyXML); For more information about XML methods, see their entries in the ActionScript Dictionary. Note: This design is only an example, and we make no claims about the level of security it provides. If you are implementing a secure password-protected system, make sure you have a good understanding of network security.
  249.  
  250. <url>html/05_integrating6.html</url>
  251. <title>Using the XMLSocket object</title> Sending and loading variables to and from a remote file Integrating Flash with Web Applications > Sending and loading variables to and from a remote file > Using the XMLSocket object ActionScript provides a predefined XMLSocket object that allows you to open a continuous connection with a server. A socket connection allows the server to push information to the client as soon as that information is available. Without a continuous connection, the server must wait for an HTTP request. This open connection removes latency issues and is commonly used for real-time applications such as chats. The data is sent over the socket connection as one string and should be in XML format. You can use the XML object to structure the data. To create a socket connection, you must create a server-side application to wait for the socket connection request and send a response to the Flash movie. This type of server-side application can be written in a programming language such as Java. You can use the ActionScript XMLSocket object's connect and send methods to transfer XML to and from a server over a socket connection. The connect method establishes a socket connection with a Web server port. The send method passes an XML object to the server specified in the socket connection. When you invoke the XMLSocket object's connect method, the Flash Player opens a TCP/IP connection to the server and keeps that connection open until one of the following happens: The close method of the XMLSocket object is called. No more references to the XMLSocket object exist. The Flash Player quits. The connection is broken (for example, the modem disconnects). The following example creates an XML socket connection and sends data from the XML object myXML. To understand the script, read the commented lines of each script as indicated by the characters // : //create a new XMLSocket object sock = new XMLSocket(); //call its connect method to establish a connection with port 1024 //of the server at the URL sock.connect("http://www.myserver.com", 1024); //define a function to assign to the sock object that handles //the servers response. If the connection succeeds, send the myXML //object. If it fails, provide an error message in a text field. function onSockConnect(success){ if (success){ sock.send(myXML); } else { msg="There has been an error connecting to "+serverName; } } //assign the onSockConnect function to the onConnect property sock.onConnect = onSockConnect; For more information, see the entry for XMLSocket in the ActionScript Dictionary.
  252.  
  253. <url>html/05_integrating7.html</url>
  254. <title>Creating forms</title> Creating forms Integrating Flash with Web Applications > Creating forms Flash forms provide an advanced type of interactivity—a combination of buttons, movies, and text fields that let you pass information to another application on a local or remote server. All common form elements (such as radio buttons, drop-down lists, and check boxes) can be created as movies or buttons with the look and feel of your Web site's overall design. The most common form element is an input text field. Common types of forms that use such interface elements include chat interfaces, order forms, and search interfaces. For example, a Flash form can collect address information and send it to another application that compiles the information into an e-mail message or database file. Even a single text field is considered a form and can be used to collect user input and display results. Forms require two main components: the Flash interface elements that make up the form and either a server-side application or client-side script to process the information that the user enters. The following steps outline the general procedure for creating a form in Flash. To create a form: 1 Place interface elements in the movie using the layout you want. You can use interface elements from the Buttons-Advanced common library or create your own. 2 In the Text Options panel, set text fields to Input and assign each a unique variable name. For more information about creating editable text fields, see Flash Help. 3 Assign an action that either sends, loads, or sends and loads the data.
  255.  
  256. <url>html/05_integrating8.html</url>
  257. <title>Creating a search form</title> Creating forms Integrating Flash with Web Applications > Creating forms > Creating a search form An example of a simple form is a search field with a Submit button. As an introduction to creating forms, the following example provides instructions for creating a search interface using a getURL action. By entering the required information, users can pass a keyword to a search engine on a remote Web server. To create a simple search form: 1 Create a button for submitting the entered data. 2 Create a label, a blank text field, and an instance of the button on the Stage. Your screen should look like this: 3 Select the text field and choose Window > Panels > Text Options. 4 In the Text Options panel, set the following options: Choose Input Text from the pop-up menu. Select Border/Bg. Specify a variable name. Note: Individual search engines may require a specific variable name. Go to the search engine's Web site for details. 5 On the Stage, select the button and choose Window > Actions. The Object Actions panel appears. Note: A check next to Actions in the Window menu indicates the panel is open. 6 Drag the getURL action from the toolbox to the Script window. 7 In the Parameters pane, set the following options: For URL, enter the URL of the search engine. For Window, select _blank . This will open a new window that displays the search results. For Variables, select Send Using GET. 8 To test the form, choose File > Publish Preview > HTML.
  258.  
  259. <url>html/05_integrating9.html</url>
  260. <title>Using variables in forms</title> Creating forms Integrating Flash with Web Applications > Creating forms > Using variables in forms You can use variables in a form to store user input. To set variables, you use editable text fields or assign actions to buttons in interface elements. For example, each item in a pop-up menu is a button with an action that sets a variable to indicate the selected item. You can assign a variable name to an input text field. The text field acts like a window that displays the value of that variable. When you pass information to and from a server-side script, the variables in the Flash movie must match the variables in the script. For example, if the script expects a variable called password , the text field into which users enter the password should be given the variable name password . Some scripts require hidden variables, which are variables that the user never sees. To create a hidden variable in Flash, you can set a variable on a frame in the movie clip that contains the other form elements. Hidden variables are sent to the server-side script along with any other variables set on the Timeline that contains the action that submits the form.
  261.  
  262. <url>html/06_troubleshooting1.html</url>
  263. <title>Troubleshooting ActionScript: Overview</title> Troubleshooting ActionScript: Overview Troubleshooting ActionScript > Troubleshooting ActionScript: Overview The level of sophistication of some actions, especially in combination with one another, can create complexity in Flash movies. As with any programming language, you can write incorrect ActionScript that causes errors in your scripts. Using good authoring techniques makes it easier to troubleshoot your movie when something behaves unexpectedly. Flash has several tools to help you test your movies in Test-Movie Mode or in a Web browser. The Debugger shows a hierarchical display list of movie clips currently loaded in the Flash Player. It also allows you to display and modify variable values as the movie plays. In Test-Movie Mode, the Output window displays error messages and lists of variables and objects. You can also use the trace action in your scripts to send programming notes and values of expressions to the Output window.
  264.  
  265. <url>html/06_troubleshooting10.html</url>
  266. <title>Using the Output window</title> Using the Output window Troubleshooting ActionScript > Using the Output window In test-movie mode, the Output window displays information to help you troubleshoot your movie. Some information, such as syntax errors, is displayed automatically. You can display other information by using the List Objects and List Variables commands. See Using List Objects and Using List Variables . If you use the trace action in your scripts, you can send specific information to the Output window as the movie runs. This could include notes about the movie's status or the value of an expression. See Using trace . To display the Output window: 1 If your movie is not running in test-movie mode, choose Control > Test Movie. 2 Choose Window > Output. The Output window appears. Note: If there are syntax errors in a script, the Output window appears automatically. 3 To work with the contents of the Output window, use the Options menu: Choose Options > Copy to copy the contents of the Output window to the Clipboard. Choose Options > Clear to clear the window contents. Choose Options > Save to File to save the window contents to a text file. Choose Options > Print to print the window contents.
  267.  
  268. <url>html/06_troubleshooting11.html</url>
  269. <title>Using List Objects</title> Using the Output window Troubleshooting ActionScript > Using the Output window > Using List Objects In test-movie mode, the List Objects command displays the level, frame, object type (shape, movie clip, or button) and target path of a movie clip instance in a hierarchical list. This is especially useful for finding the correct target path and instance name. Unlike the Debugger, the list does not update automatically as the movie plays; you must choose the List Objects command each time you want to send the information to the Output window. To display a list of objects in a movie: 1 If your movie is not running in test-movie mode, choose Control > Test Movie. 2 Choose Debug > List Objects. A list of all the objects currently on the Stage is displayed in the Output window, as in this example: Layer #0: Frame=3 Movie Clip: Frame=1 Target=_root.MC Shape: Movie Clip: Frame=1 Target=_root.instance3 Shape: Button: Movie Clip: Frame=1 Target=_root.instance3.instance2 Shape: Note: The List Objects command does not list all ActionScript data objects. In this context, an object is considered to be a shape or symbol on the Stage.
  270.  
  271. <url>html/06_troubleshooting12.html</url>
  272. <title>Using List Variables</title> Using the Output window Troubleshooting ActionScript > Using the Output window > Using List Variables In test-movie mode, the List Variables command displays a list of all the variables currently in the movie. This is especially useful for finding the correct variable target path and variable name. Unlike in the Debugger, the list does not update automatically as the movie plays; you must choose the List Variables command each time you want to send the information to the Output window. To display a list of variable in a movie: 1 If your movie is not running in test-movie mode, choose Control > Test Movie. 2 Choose Debug > List Variables. A list of all the variables currently in the movie is displayed in the Output window, as in this example: Level #0: Variable _root.country = "Sweden" Variable _root.city = "San Francisco" Movie Clip: Target="" Variable _root.instance1.firstName = "Rick"
  273.  
  274. <url>html/06_troubleshooting13.html</url>
  275. <title>Using trace</title> Using the Output window Troubleshooting ActionScript > Using the Output window > Using trace When you use the trace action in a script, you can send information to the Output window. For example, while testing a movie or scene, you can send specific programming notes to the window or have specific results appear when a button is pressed or a frame is played. The trace action is similar to the JavaScript alert statement. When you use the trace action in a script, you can use expressions as arguments. The value of an expression is displayed in the Output window in test-movie mode, as in the following: onClipEvent(enterFrame){ trace("onClipEvent enterFrame " + enterFrame++) } The trace action returns values that are displayed in the Output window.  
  276.  
  277. <url>html/06_troubleshooting2.html</url>
  278. <title>Authoring and troubleshooting guidelines</title> Authoring and troubleshooting guidelines Troubleshooting ActionScript > Authoring and troubleshooting guidelines If you use good authoring practices when you write scripts, your movies will have fewer bugs (programming errors). You can use the following guidelines to help prevent problems and to fix them quickly when they do occur.   Using good authoring practices It's a good idea to save multiple versions of your movie as you work. Choose File > Save As to save a version with a different name every half hour. You can use your version history to locate when a problem began by finding the most recent file without the problem. Using this approach, you'll always have a functioning version, even if one file gets corrupted. Another important authoring practice is to test early, test often, and test on all target platforms to find problems as soon as they develop. Choose Control > Test Movie to run your movie in test-movie mode whenever you make a significant change or before saving a version. In test-movie mode, the movie runs in a version of the stand-alone player. If your target audience will be viewing the movie on the Web, it's important to test the movie in a browser as well. In certain situations (for example, if you're developing an intranet site) you may know the browser and platform of your target audience. If you're developing for a Web site, however, test your movie in all browsers on all potential platforms. It's a good idea to follow these authoring practices: Use the trace action to send comments to the Output window. See Using trace . Use the comment action to include instructional notes that appear only in the Actions panel. See Comments . Use consistent naming conventions to identify elements in a script. For example, it's a good idea to avoid spaces in names. Start variable and function names with a lowercase letter and use a capital letter for each new word ( myVariableName , myFunctionName ). Start constructor function names with a capital letter ( MyConstructorFunction ). It's most important to pick a style that makes sense to you and use it consistently. Use meaningful variable names that reflect what kind of information a variable contains. For example, a variable containing information about the last button pressed could be called lastButtonPressed . A name like foo would make it difficult to remember what the variable contains. Use editable text fields in guide layers to track variable values as an alternative to using the Debugger. Use the Movie Explorer in Edit-Movie Mode to view the display list and view all actions in a movie. See Using Flash. Flash Help Use the for...in action to loop through the properties of movie clips, including child movie clips. You can use the for...in action with the trace action to send a list of properties to the Output window. See Repeating an action .   Using a troubleshooting checklist As with every scripting environment, there are certain mistakes that scripters commonly make. The following list is a good place to start troubleshooting your movie: Make sure you're in test-movie mode. Only simple button and frame actions (for example, gotoAndPlay , and stop ) will work in authoring mode. Choose Control > Enable Simple Frame Actions or choose Control > Enable Simple Buttons to enable these actions. Make sure you do not have frame actions on multiple layers that conflict with each other. If you're working with the Actions panel in Normal Mode, make sure your statement is set to expression. If you are passing an expression in an action and haven't selected the Expression box, the value will be passed as a string. See Using operators to manipulate values in expressions . Make sure multiple ActionScript elements do not have the same name. It's a good idea to give every variable, function, object, and property a unique name. Local variables are exceptions, though: they only need to be unique within their scope and are often reused as counters. See Scoping a variable . For more tips on troubleshooting a Flash movie, see the Flash Support Center .
  279.  
  280. <url>html/06_troubleshooting3.html</url>
  281. <title>Using the Debugger</title> Using the Debugger Troubleshooting ActionScript > Using the Debugger The Debugger allows you to find errors in a movie as it's running in the Flash Player. You can view the display list of movie clips and loaded movies and change the values of variables and properties to determine correct values. You can then go back to your scripts and edit them so that they produce the correct results. To use the Debugger, you must run the Flash Debug Player, a special version of the Flash Player. The Flash Debug Player installs automatically with the Flash 5 authoring application. It allows you to download the display list, variable name and value pairs, and property name and value pairs to the Debugger in the Flash authoring application. To display the Debugger: Choose Window > Debugger. This opens the Debugger in an inactive state. No information appears in the display list until a command is issued from the Flash Player. To activate the Debugger in test-movie mode: Choose Control > Debug Movie. This opens the Debugger in an active state.
  282.  
  283. <url>html/06_troubleshooting4.html</url>
  284. <title>Enabling debugging in a movie</title> Using the Debugger Troubleshooting ActionScript > Using the Debugger > Enabling debugging in a movie When exporting a Flash Player movie, you can choose to enable debugging in your movie and create a debugging password. If you don't enable debugging, the Debugger will not activate. As in JavaScript or HTML, any client-side ActionScript variables can potentially be viewed by the user. To store variables securely, you must send them to a server-side application instead of storing them in the movie. However, as a Flash developer, you may have other trade secrets, such as movie clip structures, that you do not want revealed. To ensure that only trusted users can watch your movies with the Flash Debug Player, you can publish your movie with a Debugger password. To enable debugging and create a password: 1 Choose File > Publish Settings. 2 Click the Flash tab. 3 Select Debugging Permitted. 4 To set a password, enter a password into the Password box. Without this password, you cannot download information to the Debugger. If you leave the password field blank, no password is required. To activate the Debugger in a Web browser: 1 Right-click (Windows) or Control-click (Macintosh) to open the Flash Debug Player context menu. 2 Choose Debugger. Note: You can use the Debugger to monitor only one movie at a time. To use the Debugger, Flash must be open. Flash Debug Player context menu  
  285.  
  286. <url>html/06_troubleshooting5.html</url>
  287. <title>About the status bar</title> Using the Debugger Troubleshooting ActionScript > Using the Debugger > About the status bar Once activated, the Debugger status bar displays the URL or local file path of the movie. The Flash Player is implemented in different forms depending on the playback environment. The Debugger status bar displays the type of Flash Player running the movie: Test-movie mode Stand-alone player Netscape plug-in The Netscape plug-in is used with Netscape Navigator on Windows and Macintosh and in Microsoft Internet Explorer on Macintosh. ActiveX control The ActiveX control is used with Internet Explorer on Windows.
  288.  
  289. <url>html/06_troubleshooting6.html</url>
  290. <title>About the display list</title> Using the Debugger Troubleshooting ActionScript > Using the Debugger > About the display list When the Debugger is active, it shows a live view of the movie clip display list. You can expand and collapse branches to view all movie clips currently on the Stage. When movie clips are added to or removed from the movie, the display list reflects the changes immediately. You can resize the display list by moving the horizontal splitter or by dragging from the bottom right corner.
  291.  
  292. <url>html/06_troubleshooting7.html</url>
  293. <title>Displaying and modifying variables</title> Using the Debugger Troubleshooting ActionScript > Using the Debugger > Displaying and modifying variables The Variables tab in the Debugger displays the names and values of any variables in the movie. If you change the value of a variable in the Variables tab, you can see the change reflected in the movie while it runs. For example, to test collision detection in a game, you could enter the variable value to position a ball in the correct location next to a wall. To display a variable: 1 Select the movie clip containing the variable from the display list. 2 Click the Variables tab. The display list updates automatically as the movie plays. If a movie clip is removed from the movie at a specific frame, that movie clip is also removed from the display list in the Debugger; this removes the variable name and value. To modify a variable value: Select the value and enter a new value. The value must be a constant value (for example, " Hello" , 3523, or " http://www.macromedia.com" ), not an expression (for example, x + 2 , or eval("name:" +i) ). The value can be a string (any value surrounded by quotation marks ( "" )), a number, or a Boolean ( true or false ). Object and Array variables are displayed in the Variables tab. Click on the Add (+) button to see their properties and values. However, you can't enter Object or Array values (for example, {name: "I am an object"} or [1, 2, 3] ) in the values fields. Note: To output the value of an expression in test-movie mode, use the trace action. See Using trace .
  294.  
  295. <url>html/06_troubleshooting8.html</url>
  296. <title>Using the Watch list</title> Using the Debugger Troubleshooting ActionScript > Using the Debugger > Using the Watch list To monitor a set of critical variables in a manageable way, you can mark variables to appear in the Watch list. The Watch list displays the absolute path to the variable and the value. You can also enter a new variable value in the Watch list. Only variables can be added to the Watch list, not properties or functions. Variables marked for the Watch list and variables in the Watch list   To add variables to the Watch list, do one of the following: In the Variables tab, right-click (Windows) or Control-click (Macintosh) a selected variable and choose Watch from the context menu. A blue dot appears next to the variable. In the Watch tab, right-click (Windows) or Control-click (Macintosh) and choose Add from the context menu. Enter the variable name and value in the fields. To remove variables from the Watch list: In the Watch tab, right-click (Windows) or Control-click (Macintosh) and choose Remove from the context menu.
  297.  
  298. <url>html/06_troubleshooting9.html</url>
  299. <title>Displaying movie properties and changing editable properties</title> Using the Debugger Troubleshooting ActionScript > Using the Debugger > Displaying movie properties and changing editable properties The Debugger Properties tab displays all the property values of any movie clip on the Stage. You can change the value of a property and see the change reflected in the movie while it runs. Some movie clip properties are read-only and cannot be changed. To display a movie clip's properties: 1 Select a movie clip from the display list. 2 Click the Properties tab. The Properties tab in the Debugger   To modify a property value: Select the value and enter a new value. The value must be a constant (for example, 50 , or "clearwater" ) rather than an expression (for example, x + 50 ). The value can be a string (any value surrounded by quotation marks ( "" )), a number, or a Boolean ( true or false ). You can't enter object or array values (for example, {id: "rogue"} or [1, 2, 3] ) in the Debugger. For more information, see String and Using operators to manipulate values in expressions . Note: To output the value of an expression in test-movie mode, use the trace action. See Using trace .
  300.  
  301. <url>html/08_appendix_a1.html</url>
  302. <title>Operator List</title> Operator List Operator Precedence and Associativity > Operator List This table lists all of Action Script operators and their associativity, from highest to lowest precedence. Operator Description Associativity Highest Precedence + Unary plus Right to left - Unary minus Right to left ~ Bitwise one's complement Right to left ! Logical NOT Right to left not Logical NOT (Flash 4 style) Right to left ++ Post-increment Left to right -- Post-decrement Left to right ( ) Function call Left to right [ ] Array element Left to right . Structure member Left to right ++ Pre-increment Right to left -- Pre-decrement Right to left new Allocate object Right to left delete Deallocate object Right to left typeof Type of object Right to left void Returns undefined value Right to left * Multiply Left to right / Divide Left to right % Modulo Left to right + Add Left to right add String concatenation (formerly &) Left to right - Subtract Left to right << Bitwise Left Shift Left to right >> Bitwise Right Shift Left to right >>> Bitwise Right Shift (Unsigned) Left to right < Less than Left to right <= Less than or equal to Left to right > Greater than Left to right >= Greater than or equal to Left to right lt Less than (string version) Left to right le Less than or equal to (string version) Left to right gt Greater than (string version) Left to right ge Greater than or equal to (string version) Left to right == Equal Left to right != Not equal Left to right eq Equal (string version) Left to right ne Not equal (string version) Left to right & Bitwise AND Left to right ^ Bitwise XOR Left to right | Bitwise OR Left to right && Logical AND Left to right and Logical AND (Flash 4) Left to right || Logical OR Left to right or Logical OR (Flash 4) Left to right ?: Conditional Right to left = Assignment Right to left "*=, /=, %=, +=, -=, &=, |=, ^=, <<=, >>=, >>>=" Compound assignment Right to left , Multiple evaluation Left to right Lowest Precedence
  303.  
  304. <url>html/09_appendix_b1.html</url>
  305. <title>Keyboard keys and key code values: Overview</title> Keyboard keys and key code values: Overview Keyboard Keys and Key Code Values > Keyboard keys and key code values: Overview The following tables list all of the keys on a standard keyboard and the corresponding key code values that are used to identify the keys in ActionScript. For more information, see the description of the Key object in the Action Script dictionary.
  306.  
  307. <url>html/09_appendix_b2.html</url>
  308. <title>Letters A to Z and standard numbers 0 to 9 Letter or number key Key code A 65 B 66 C 67 D 68 E 69 F 70 G 71 H 72 I 73 J 74 K 75 L 76 M 77 N 78 O 79 P 80 Q 81 R 82 S 83 T 84 U 85 V 86 W 87 X 88 Y 89 Z 90 0 48 1 49 2 50 3 51 4 52 5 53 6 54 7 55 8 56 9 57</title> Letters A to Z and standard numbers 0 to 9 Keyboard Keys and Key Code Values > Letters A to Z and standard numbers 0 to 9
  309.  
  310. <url>html/09_appendix_b3.html</url>
  311. <title>Keys on the numeric keypad Numeric keypad key Key code Numbpad 0 96 Numbpad1 97 Numbpad 2 98 Numbpad 3 99 Numbpad 4 100 Numbpad 5 101 Numbpad 6 102 Numbpad 7 103 Numbpad 8 104 Numbpad 9 105 Multiply 106 Add 107 Enter 108 Subtract 109 Decimal 110 Divide 111</title> Keys on the numeric keypad Keyboard Keys and Key Code Values > Keys on the numeric keypad
  312.  
  313. <url>html/09_appendix_b4.html</url>
  314. <title>Function keys Function key Key code F1 112 F2 113 F3 114 F4 115 F5 116 F6 117 F7 118 F8 119 F9 120 F10 121 F11 122 F12 123</title> Function keys Keyboard Keys and Key Code Values > Function keys
  315.  
  316. <url>html/09_appendix_b5.html</url>
  317. <title>Other keys Key Key code Backspace 8 Tab 9 Clear 12 Enter 13 Shift 16 Control 17 Alt 18 Caps Lock 20 Esc 27 Spacebar 32 Page Up 33 Page Down 34 End 35 Home 36 Left Arrow 37 Up Arrow 38 Right Arrow 39 Down Arrow 40 Insert 45 Delete 46 Help 47 Num Lock 144 ; : 186 = + 187 - _ 189 / ? 191 \Q ~ 192 [ { 219 \ | 220 ] } 221 '' ' 222</title> Other keys Keyboard Keys and Key Code Values > Other keys
  318.  
  319. <url>html/10_appendix_c1.html</url>
  320. <title>Table of error messages</title> Table of error messages Error Messages > Table of error messages The following table contains a list of error messages returned by the Flash compiler. An explanation of each message is provided to aid you in troubleshooting your movie files. Error message Description Property <property> does not exist A property that does not exist was encountered. For example, x = _green is invalid, because there is no _green property. Operator <operator> must be followed by an operand An operator without an operand was encountered. For example, x = 1 + requires an operand after the + operator. An operator is followed by an invalid operand. For example, trace(1+); is syntactically incorrect. Syntax error This message is issued whenever a nonspecific syntax error is encountered. Expected a field name after '.' operator You must specify a valid field name when using the object.field syntax. Expected <token> An invalid or unexpected token was encountered. For example, in the syntax below, the token foo is not valid. The expected token is while . do { trace (i) } foo (i < 100) Initializer list must be terminated by <terminator> An object or array initializer list is missing the closing ] or }. Identifier expected An unexpected token was encountered in place of an identifier. In the example below, 3 is not a valid identifier. var 3 = 4; The JavaScript '<construct>' construct is not supported A JavaScript construct that is not supported by ActionScript was encountered. This message appears if any of the following JavaScript constructs are used: void , switch , try , catch , or throw . Left side of assignment operator must be variable or property An assignment operator was used, but the left side of the assignment was not a legal variable or property. Statement block must be terminated by '}' A group of statements was declared within curly braces, but the closing brace is missing. Event expected An On(MouseEvent) or onClipEvent handler was declared, but no event was specified, or an unexpected token was encountered where an event should appear. Invalid event The script contains an invalid mouse or clip event. For a list of valid mouse and clip events, see the On(MouseEvent) and OnClipEvent entries in the ActionScript dictionary chapter. Key code expected You need to specify a key code. See Appendix B for a list of key codes. Invalid key code The specified key code does not exist. Trailing garbage found The script or expression parsed correctly but contained additional trailing characters that could not be parsed Illegal function A named function declaration was used as an expression. Named function declarations must be statements. Valid: function sqr (x) { return x * x; } Invalid: var v = function sqr (x) { return x * x; } Function name expected The name specified for this function is not a valid function name. Parameter name expected A parameter (argument) name was expected in a function declaration, but an unexpected token was encountered. 'else' encountered without matching 'if' An else statement was encountered, but no if appeared before it. You can use else only in conjunction with an if statement. Scene type error The scene argument of a gotoAndPlay , gotoAndStop , or ifFrameLoaded action was of the wrong type. The scene argument must be a string constant. Internal error An internal error occurred in the ActionScript compiler. Please send the FLA file that generated this error to Macromedia, with detailed instructions on how to reproduce the message. Hexadecimal digits expected after 0x The sequence 0x was encountered, but the sequence was not followed by valid hexadecimal digits. Error opening #include file There was an error opening a file included with the include directive. The error may have occurred because the file was not present or because of a disk error. Malformed #include directive An include directive was not written correctly. An include directive must use the following syntax: #include " somefile .as" Multi-line comment was not terminated A multi-line comment started with /* is missing the closing */ tag. String literal was not properly terminated A string literal started with an opening quotation mark (single or double) is missing the closing quotation mark. Function <function> takes <count> parameters A function was called, but an unexpected number of parameters were encountered. Property name expected in GetProperty The getProperty function was called, but the second argument was not the name of a movie clip property. Parameter <parameter> cannot be declared multiple times A parameter name appeared multiple times in the parameter list of a function declaration. All parameter names must be unique. Variable <variable> cannot be declared multiple times A variable name appeared multiple times in a var statement. All variable names in a single var statement must be unique. 'on' handlers may not be nested within other 'on' handlers An on handler was declared inside another on handler. All on handlers must appear at the top level of an action list. Statement must appear within on handler In the actions for a button instance, a statement was declared without a surrounding on block. All actions for a button instance must appear inside an on block. Statement must appear within onClipEvent handler In the actions for a movie clip instance, a statement was declared without a surrounding onClipEvent block. All actions for a movie clip instance must appear inside an onClipEvent block. Mouse events are permitted only for button instances A button event handler was declared in a frame action list or a movie clip instance's action list. Button events are permitted only in the action lists of button instances. Clip events are permitted only for movie clip instances A clip event handler was declared in a frame action list or a button instance's action list. Clip events are permitted only in the action lists of movie clip instances.
  321.  
  322. <url>html/90cred1.html</url>
  323. <title></title> Acknowledgments Project Management: Erick Vera Writing: Jody Bleyle, Mary Burger, Louis Dobrozensky, Stephanie Gowin, Marcelle Taylor, and Judy Walthers Von Alten Editing: Peter Fenczik, Rosana Francescato, Ann Szabla Multimedia: George Brown, John “Zippy” Lehnus, and Noah Zilberberg Print and Help Design: Chris Basmajian and Noah Zilberberg Production: Chris Basmajian and Rebecca Godbois Special thanks: Jeremy Clark, Brian Dister and the entire Flash Development team, Margaret Dumas, Kipling Inscore, Alyn Kelley and the entire Flash QA team, Pete Santangeli, Cyn Taylor, and Eric Wittman
  324.  
  325. <url>html/90cred2.html</url>
  326. <title></title> Trademarks & Disclaimers Trademarks Afterburner, AppletAce, Attain, Attain Enterprise Learning System, Attain Essentials, Attain Objects for Dreamweaver, Authorware, Authorware Attain, Authorware Interactive Studio, Authorware Star, Authorware Synergy, Backstage, Backstage Designer, Backstage Desktop Studio, Backstage Enterprise Studio, Backstage Internet Studio, Design in Motion, Director, Director Multimedia Studio, Doc Around the Clock, Dreamweaver, Dreamweaver Attain, Drumbeat, Drumbeat 2000, Extreme 3D, Fireworks, Flash, Fontographer, FreeHand, FreeHand Graphics Studio, Generator, Generator Developer's Studio, Generator Dynamic Graphics Server, Knowledge Objects, Knowledge Stream, Knowledge Track, Lingo, Live Effects, Macromedia, Macromedia M Logo & Design, Macromedia Flash, Macromedia Xres, Macromind, Macromind Action, MAGIC, Mediamaker, Object Authoring, Power Applets, Priority Access, Roundtrip HTML, Scriptlets, SoundEdit, ShockRave, Shockmachine, Shockwave, Shockwave Remote, Shockwave Internet Studio, Showcase, Tools to Power Your Ideas, Universal Media, Virtuoso, Web Design 101, Whirlwind and Xtra are trademarks of Macromedia, Inc. and may be registered in the United States or in other jurisdictions including internationally. Other product names, logos, designs, titles, words or phrases mentioned within this publication may be trademarks, servicemarks, or tradenames of Macromedia, Inc. or other entities and may be registered in certain jurisdictions including internationally. This guide contains links to third-party Web sites that are not under the control of Macromedia, and Macromedia is not responsible for the content on any linked site. If you access a third-party Web site mentioned in this guide, then you do so at your own risk. Macromedia provides these links only as a convenience, and the inclusion of the link does not imply that Macromedia endorses or accepts any responsibility for the content on those third-party sites. Apple Disclaimer APPLE COMPUTER, INC. MAKES NO WARRANTIES, EITHER EXPRESS OR IMPLIED, REGARDING THE ENCLOSED COMPUTER SOFTWARE PACKAGE, ITS MERCHANTABILITY OR ITS FITNESS FOR ANY PARTICULAR PURPOSE. THE EXCLUSION OF IMPLIED WARRANTIES IS NOT PERMITTED BY SOME STATES. THE ABOVE EXCLUSION MAY NOT APPLY TO YOU. THIS WARRANTY PROVIDES YOU WITH SPECIFIC LEGAL RIGHTS. THERE MAY BE OTHER RIGHTS THAT YOU MAY HAVE WHICH VARY FROM STATE TO STATE. Copyright © 2000 Macromedia, Inc. All rights reserved. These Help Pages may not be copied, photocopied, reproduced, translated, or published in any electronic or machine-readable form in whole or in part without prior written approval of Macromedia, Inc. First Edition: July 2000 Macromedia, Inc. 600 Townsend St. San Francisco, CA 94103
  327.  
  328. <url>html/mimetype.html</url>
  329. <title></title> Using Flash Help&--Overview Adding the SWF MIME type for Macintosh Internet Explorer users The movies in Flash Help are Shockwave Flash movies. They are installed on your local hard drive. To use Internet Explorer 3.0 or 4.0 on a Macintosh to view these movies or any Shockwave Flash movies stored locally, you must change your Internet Explorer MIME type Preferences. To add the SWF MIME type to your Internet Explorer browser preferences on a Macintosh: 1 Launch Internet Explorer. 2 Choose Edit Preferences. 3 Under Receiving Files, choose File Helpers. 4 Click Add to add the following information: Representation: Description: Shockwave Flash Extension: .swf MIME type: application/x-shockwave-flash File Type: Application: Flash (browse to where your local copy of Flash is located) File Type: SWFL File Creator: MFL2 Handling: How to handle: View with Plugin Application: Shockwave Flash NP-PPC or Shockwave Flash NP-68K (Browse to the appropriate plugin for your machine.) 5 Click OK. Note: In some versions of Internet Explorer, you may need to repeat this process twice in order to make the changes take effect. 6 Click the browser's Back button to return to the help topic. To view older FutureSplash files, repeat these steps with SPL.
  330.  
  331.